Problem getting cin.get() to work...

Started by
2 comments, last by rip-off 12 years, 2 months ago
I wrote this little program the 1st day I started coding and mess around with it to try out new functions I learn occasionally. I added cin.get() to the end of it, open it up outside of my compiler, and it still closes the window before I can read the final line of text. Any ideas?


#include <iostream>

int daily(int i, int h);
int travel(int t, int d);

int main()
{
using namespace std;
cout << "What is your hourly pay?" << endl;
int i;
cin >> i;
cout << "How many days is the job?" << endl;
int d;
cin >> d;
cout << "How many hours per day(including overtime)?" << endl;
int h;
cin >> h;
cout << "Finally, how much per diem do you make per day?" << endl;
int t;
cin >> t;
cout << "You make $" << daily(i, h) * d + travel(t, d) << " gross on this job." << endl;
cin.get();
return 0;
}

I also read http://www.gidnetwork.com/b-61.html and didn't want to use system("pause") based on it.
Advertisement
add cin.ignore() before cin.get() to clear the input stream (cin>>t will leave the return/newline in the stream and cin.get will pick that up)

For serious console apps however you don't want to pause the execution in the end as it makes it harder to get it working properly with pipes or scripts, console apps are meant to run from the console.
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
http://www.cprogramming.com/tips/tip/clean-up-after-cin-cincrement

I guess it's by design...funny, but I haven't written input code with the input operators since college. Many engine code bases use the old school c style input functions sscanf
http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
That looks like a nice program for your first day. When you've got it working the way you want, you might be wondering if there is any scope for improvement. One issue with your current program is that if the user enters something that isn't a number, your program doesn't notice and the user will get some rather surprising results at the end.

You can check if the user entered invalid input using code like the following:

int variable;
if(cin >> variable)
{
// User entered an integer!
}
else
{
// Something went wrong...
// We didn't give "variable" a known value, so we cannot depend on it having any particular value here.
}

A simple exercise is to ensure the user is notified if they enter invalid input, and to not continue the program if they do. A more complicated exercise is to allow the program to recover from such a mistake. If you are familiar with loops then you might want to try this.

This topic is closed to new replies.

Advertisement