using cin and cout in textmate - c++

I am usually a Java programmer, and have used textmate for that almost exclusively, but lately I started using C++ with it. but when i use even the most basic programs and incorporate the cin keyword, and run the program, I dont get an oppurtunity to put in anything during runtime and sometimes it inserts random values by itself! for example, if i ran this in textmate:
#include <iostream>
int stonetolb(int);
int main() {
using namespace std;
int stone;
cout << "enter the weight in stone";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << "stone = ";
cout << pounds <<" pounds.";
return 0;
}
int stonetolb(int sts) {
return 14 * sts;
}
I would come out with the output:
enter the weight in stone32767stone = 458738 pounds.
Why is this happening, and how do I stop it?

Most likely, the input statement cin >> stone is failing, and stone has an undefined value. You need to check for input failure by using if (cin >> stone) { ... } else { // input failure }. As for why such a simple program would exhibit failing behaviour, I don't know- you would have to check the textmate documentation.

Related

For Loops (C++)

Assignment:
The program should ask the user to enter a positive number and display all numbers from 1 to the input value. If the number is not positive, an error message should show up asking the user to re - enter the number.
My specific problem:
For my program, if the user enters an incorrect number and then re - enters a positive number, it does not display all the numbers from 1 to the input value. The program just ends.
#include <iostream>
using namespace std;
int main()
{
int userChoice;
int i = 1;
cout << "Enter a positive integer" << endl;
cin >> userChoice;
if (userChoice > 0)
{
for (i = 1; i <= userChoice; i++)
{
cout << "Loop 1:" << endl;
cout << i << endl;
}
}
else if (userChoice < 0)
cout << "Please re - enter" << endl;
cin >> userChoice;
system("pause");
return 0;
}
You need some sort of loop at the top of your program, that keeps asking for input until the user provides something valid. It looks like a homework assignment, so I will provide pseudo-code, not something exact:
std::cout << "Enter a number:\n";
std::cin >> choice;
while (choice wasn't valid) { // 1
tell the user something went wrong // 2
ask again for input in basically the same way as above // 3
}
// after this, go ahead with your for loop
It is actually possible to avoid the duplication here for step 3, but I worry that might be a little confusing for you, so one duplicated line really isn't such a big problem.
As an aside, you may wish to reconsider your use of what are often considered bad practices: using namespace std; and endl. (Disclaimer - these are opinions, not hard facts).

Nesting int main() inside int main()

I am trying to make the simplest of all games, but with a loop function.
I'm given the error "a function-definition is not allowed here before '{', as well as a whole list of [Error] expected '}' at end of input.
Am I not allowed to nest int main() within another? Is that my issue at all? How do I accomplish this code without the nesting?
My knowledge and experience extend no more than a few chapters in two books.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
int main()
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
}
cout << "\n\tWould you like to play again? (y/n): ";
char again;
cin >> again;
}
Your issue is nesting a main function inside of the existing main function. (This is not allowed.) In general, (With the exception of some stuff you can do with structs/lambdas which approximate that kind of functionality) you shouldn't nest functions inside of each-other. If you merely remove the function declaration, then your code should work fine:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
cout << "\n\tWould you like to play again? (y/n): ";
cin >> again;
}
}
As far as I know, you cannot nest int main() inside of int main() for a number of reasons. In general, you can't define one function inside of another (defining "locally"). However, even if you can, your desire to do so should be a massive red flag that your design is off.
NOTE: As Nathan Oliver pointed out in the comments, you can forward-declare a function "locally" (within another function), but the actual implementation must be outside. Even doing this, you should usually second-guess your design at this point.
You need to be asking yourself what you're trying to do.
Are you wanting to group code together under a function to call repeatedly? Then create a separate function (with a different name) outside of main().
Are you wanting to repeat code? If so, you need a loop or a recursive function structure.
Are you wanting to split up some behavior into several functions, but hide all but one function involved? If so, look into classes (not necessarily objects - you can also have static classes.)
Those are just three of many possibilities, and deciding exactly what you want to do and how you want to do it is your responsibility alone to decide, as a programmer.
Brief recap: as far as C++ (and C) are concerned, if you're trying to declare any function inside any other function, you are doing something seriously wrong in design.
On a more technical note, you should also understand precisely what int main() is. It is a special function that is the entry point for your program. No C or C++ program can run without an int main().
You have to have a single instance of this function in main.cpp in order for your program to work. If you have more than one int main(), the computer cannot likely will not be able to find the entry point.
Besides that, having more than one function called main() anywhere in your code is a great way to confuse yourself and others.
In short, you should only have one int main() per program, no exceptions.

Why does a cout statement at the beginning of my program not output anything?

So I'm working on some code for a class. Yes I know the input validation I'm trying to work out is inefficient and the program is unfinished. I don't need the rest of it to work. Here's the code.
/*Write a program that allows the user to enter a payroll code.
The program should search for the payroll code in the file and then display the appropriate salary.
If the payroll code is not in the file, the program should display an appropriate message.
Use a sentinel value to end the program.*/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
int code;
ifstream PayrollFile;
int FCode;
int Salary;
char Trash;
string line;
string lineTwo;
int NumOfCodes=0;
int Subscript=0;
cout << "everything is starting";
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
do{
lineTwo=line;
PayrollFile >> line;
NumOfCodes++;
}
while (line!=lineTwo);
PayrollFile.close();
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
int ListOfPayrollCodes[NumOfCodes-1];
while (Subscript<NumOfCodes){
while (PayrollFile >> FCode >> Trash >> Salary) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
}
PayrollFile.close();
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
cout << "please enter the payroll code";
cin >> code;
while (PayrollFile >> FCode >> Trash >> Salary) {
if (code==FCode) {
cout << "The salary is " << Salary << endl;
}
}
PayrollFile.close();
}
The thing I'm confused about is the fact that the compiler never seems to reach this line:
cout << "everything is starting";
As far as I can tell, there is nothing before this line that should stop the program from outputting "everything is starting" but "everything is starting" never shows up in the output.
The code builds and begins running but never stops and fails to output anything. My teacher couldn't figure this out either.
I'm running OSX10.9 and using XCode for my compiler. I've tried other compilers with the same results.
Thanks!
In these loops:
while (Subscript<NumOfCodes){
while (PayrollFile >> FCode >> Trash >> Salary) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
}
If extraction fails, PayrollFile starts converting to false, and there's no longer any way for Subscript to increase. So the outer loop never terminates.
Instead use:
while ((Subscript<NumOfCodes) && (PayrollFile >> FCode >> Trash >> Salary)) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
For your printf-debugging needs, when using cout, also use std::flush or std::endl. Otherwise the output will be buffered, and not help you learn where your program got stuck. (For actually writing out large quantities of data, you'll want to avoid flushing any more than necessary, because it kills performance.)
Use breakpoints. when you started to debug check if they are still red or turned white. if turned white you can see a note there about the situation. if its red and you cant reach it means its never getting there.
cout is a buffered stream; to force the output you should
using endl manipulator;
usinf flush() method
int ListOfPayrollCodes[NumOfCodes-1]; - // This line should not compile.You're using a variable to declare the size of an array . This is supposed to be a constant.
I'm not sure how you compile this code. Please fix a constant and see, how it sounds. I hardcoded it and commented the Numcodes increment line and I could print it.
Update: Ok, Looks like you're saying the compiler does not reach this line. That means, the code does not compile. The reason is above.
I understand that you want an array of size ListOfPayrollCodes. Use dynamic allocation as opposed to static allocation, it will work fine.

How to make the user type a value instead of storing a constant value?

I have made a simple program in C++ and this is the code:
#include <iostream>
using namespace std;
int main()
{
int number;
int square;
number = 5;
square = number * number;
cout << "The square is ";
cout << square;
return 0;
}
what it does is basically taking the integer "5" and get the square value on the screen and so on...
my question is:
how can I make the program take any value from the user instead of storing a value in the memory?
than Q.
Your code makes use of cout to print. C++ makes cin available for input from the console:
int x;
cin >> x;
"An example is worth a thousand words..."
Well cout takes some var. from memory and prints it out on the screen, right?
Well, cin does the exact opposite, it takes in some value from the keyboard and puts it in your memory..
You have to take in the value with the help of cin command, like this:
int a; //lets say you have a variable
cout << "Enter a value here: "; //prompts the user to enter some number
cin >> a; //this line will allow the user to enter some value with the keyboard into this var.
int square = a * a;
cout << "The square is: " << square;
Hope it helps...
Just replace:
number = 5;
with:
cout << "What's the number? ";
cin >> number;
You already know how to use cout to generate output, this simply uses cin to retrieve input.
Keep in mind that, while this may be okay for small test programs or learning, data input in real programs tends to be a little more robust (such as if you enter the string xyzzy when it's trying to input an int variable).

(cin >> int).get() doesn't properly work in Xcode(4.3.3)

I'm currently working on the book "C++ Primer Plus" and doing some of the programming excersis.
As it seems, I'm having a problem with Xcode(4.3.3) because following code doesn't work how it's supposed to work:
#include <iostream>
#include <string>
struct car
{
std::string maker;
int year;
};
int main()
{
using namespace std;
cout << "How many cars do you wish to catalog? ";
int nCars;
(cin >> nCars).get();
car* aCars = new car[nCars];
for (int i = 0; i < nCars; i++)
{
cout << "\nCar #" << (i + 1) << endl;
cout << "Please enter the make: ";
getline (cin, (aCars + i)->maker);
cout << "\nPlease enter the year made: ";
(cin >> (aCars + i)->year).get();
}
cout << "Here is your collection: \n";
for (int i = 0; i < nCars; i++)
{
cout << (aCars + i)->year << " " << (aCars + i)->maker << endl;
}
delete [] aCars;
return 0;
}
The problem is, I don't have the chance to enter any maker. The program directly goes to the point where I have to enter the year, even though I'm using "(cin >> nCars).get();" to get rid of the newline character.
Am I overlooking something?
Thanks in advance!
I suspect that you may be running on windows and the two-byte newlines are hitting you. You may be able to improve things (for lines that aren't ridiculously long) with ignore:
cin >> nCars;
cin.ignore(1024, '\n');
Note that since you rely on stream numeric processing, entering a non-numeric year such as QQ will result in the programming just finishing without asking for any more input.
You don't need to do math on the years so treat them as strings instead of integers. Then if you need to you can do validation of each year after you get the input.
Ok, guys..I found the problem.
The console within Xcode doesn't work as expected when using cin.get().
I tried the same code in the terminal as well as with Visual Studio (Win 7) and the program works perfectly.
Anyway, thank you all for your advices. I'll try consider them the next time. :)
Cheers!