I am just working through the book Accelerated C++. (My problem is located on page 57, if you guys have the book with you)
The problem is the following: We do have a function which reads student grades:
...
while (in >> x) { // in and x are defined as an istream& and as a double
hw.push_back(x); // hw is vector defined as vector<double>&
}
in.clear();
...
Now, in book and also on the cplusplus.com refernce is stated that the clear function resets all the error states and that the input is now again ready to read some input. The problem is that if I put a:
int a = 0;
cin >> a;
cout << a << endl;
after the function it jumps the cin and just gives me a 0. Did I understand the function of cin.clear() totally wrong or what can I do to get the cin active again.
As I had the same problem a while before I read the book, I know that I solved the problem back then with the following line:
cin.ignore( numeric_limits<streamsize>::max(), '\n');
Of course I then have to hit an extra enter key but it eats all the stuff which comes before and which makes the cin not to work.
The thing is that neither .clear nor .ignore work properly alone but using them both together I am able to enter something for the variable a;
EDIT: Ok, here is the whole code. This is something I have written myself, which is not from the book.
istream& in = cin;
int var = 0;
vector<int> vec;
while ( in >> var ) {
vec.push_back(var);
}
for (int f = 0; f < vec.size(); ++f) {
cout << vec[f] << endl;
}
cin.clear();
cout << "cleared" << endl;
int a = 0;
cin >> a;
cout << a << endl;