Reputation: 3813
I'm using C++ for the first time from PHP. I was playing around with some code. To my understanding cin.get();
was suppose to stop the window from closing until I press a key, however it doesn't seem to be working because of the code before it, I don't know what the problem is. Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int multiply (int x, int y);
int main ()
{
int x;
int y;
cout << "Please enter two integers: ";
cin >> x >> y;
int total = multiply(x, y);
cout << total;
cin.get();
}
int multiply (int x, int y) {
return x*y;
}
Upvotes: 1
Views: 5376
Reputation: 31
You may use
cin.ignore(256,'\n');
just before the final
cin.get();
This discards the unintentional '\n' keyed in as part of reading x and y. The page stops from closing till an additional key press as desired.
Upvotes: 3
Reputation: 8164
Put a
cin.ignore(numeric_limits<streamsize>::max(),'\n')
after >> x >> y;
(or before cin.get()
).
This flushes the buffer of cin
and deletes the pending \n
which is still there, because you cin
reads x and y but also reads the last return (after y). This gets read in when you call cin.get()
. If you flush the buffer cin.get()
will see an empty buffer and everything is fine.
Upvotes: 5
Reputation: 361792
It reads the newline character which is still left present in the input stream as the previous read could extract it from the stream.
See this:
cin >> x >> y;
It only reads two integers, but it doesn't read the newline character which was entered when you hit the button.
Upvotes: 1