why do i need to use cin.get twice???

Hey guys, i was writing a very simple program and came a across an problem. In order to stop my program from closing i had to use cin.get () twice? Is this normal ? here is my code -

int main()
{
int a;
int b;
int sum;


cout << "To start this addition calculator, please enter a number!" << endl << endl;

cin >> a;

cout << "Now enter another number !" << endl << endl;

cin >> b;

sum = a + b;

cout << "The sum of those two numbers is " << sum << endl << endl;

cout << "This program was created by Omar Ismail" << endl <<endl;

cout << "Press enter to continue..." ;



cin.get ();
cin.get ();

return 0;
}
Yes, it is kinda normal, You must flush the input stream (cin is the input stream) first. I just don't remember how. Look for flush/fflush or similar.
When you're reading an integer with cin >> a;, you're typing <digit> <digit> <digit> <digit> <ENTER> on the keyboard.
operator>> for integers consumes the digits, but goes no further, the <ENTER> is still waiting to be processed.

Your first cin.get() reads and returns that <ENTER> as the character '\n', which you don't assign anywhere.

Your second cin.get() reads and returns the next character to be entered, and since there's nothing after that Enter, it waits.

Note that if you enter <digit> <digit> <digit> <SPACE> <ENTER>, your double-cin-get will fail: the first will read the space, the second will read the enter, and the program will complete immediately. If you want to be bulletproof, read and discard everything first: cin.ignore(numeric_limits<streamsize>::max(), '\n'); (that's what is sometimes called "flushing" the input, although the concept of flushing doesn't apply to inputs)
Topic archived. No new replies allowed.