Sorry to bother you with this, but sometimes when I do cin >> nbr; following a previous cin >> operation, the cin fails. It doesn't read anything and just skips right by it.
I'm just getting back into C++ and had the same problem years ago. At that time, I always followed cin >> nbr; with: cin.get(); the get() seems to clean up the input stream, or something. I still don't understand what is really going on here, and there must be an explanation and a better way.
Here is a current example:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter one or more numbers followed by Enter and Cntl+d" << endl;
double x = 0;
int tot = 0;
while (cin>>x) ++tot;
cout << "Last entered x = " << x << endl;
// The following cin fails
int nbr = 0;
cout << "Enter a number" << endl;
cin >> nbr; // This Fails
cout << '\n' << The value of nbr is " << nbr << endl;
return 0;
}
/*
Enter one or more numbers followed by Enter and Cntl+d
4 5
Last entered x = 5
Enter a number:
The value of nbr is 0
*/
Of course the problem here might have something to do with the termination of the previous cin,
being: Enter Cntl+d for EOF
However, I've had this problem in other places. I'm sure someone has an idea for me.
Once EOF (or any other error) is signalled, all attempts to input data fail. You must first clear the stream (cin.clear();) before attempting further input.
1 2 3 4 5 6 7 8 9 10
cout << "Last entered x = " << x << endl;
// Clear the EOF condition on the standard input
cin.clear();
// Now this will not fail
int nbr = 0;
cout << "Enter a number" << endl;
cin >> nbr; // Works fine...