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.
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
unsigned number_of_numbers = 0;
double sum_of_numbers = 0.0;
cout << "Please enter one or more numbers. Press ENTER twice to finish.\n> " << flush;
string s;
while (getline( cin, s ) && !s.empty())
{
istringstream ss( s );
double x;
while (ss >> x)
{
number_of_numbers += 1;
sum_of_numbers += x;
}
if (!ss.eof())
cout << "Only enter numbers please!\n";
cout << "> " << flush;
}
cout << "You entered " << number_of_numbers << " numbers.\n";
cout << "Their sum is " << sum_of_numbers << ".\n";
cout << "The average is " << (sum_of_numbers / number_of_numbers) << ".\n";
return 0;
}
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...