I was recently reading a C++ textbook (Accelerated C++) and the author wants to read input data of the form:
name1 double double double double ...
name2 double double double double ...
^ all doubles from here on out will go into a vector
The author's idea is to do do something like read from cin until the stream fails, which it will do either because the input is finished, or because we try reading name2 as a double which will put the stream into a fail state. In regards to this he says
In either case, then, we would like to pretend that we never saw whatever followed the last homework grade. Such pretense turns out to be easy: if we encountered something that wasn't a grade, the library will have left it unread for the next input attempt. Therefore all we need to do is tell the library to disregard whatever condition caused the input attempt to fail, be it eof or invalid input.
My question relates to the bolded part. The author seems to be implying that a failed attempt at reading from cin will not discard the token that it failed on, but rather leave it in the stream. However, I wrote a program to test this and this does't seem to be the case:
Input data (i've put it all on one line for simplicity):
p1 90 91 92 93 94 p2 81 82 83 84 85
Program:
using std::cout; using std::cin;
using std::endl; using std::string;
int main() {
while(cin) {
string name, midterm, final;
cin >> name >> midterm >> final;
double x;
cout << endl << "Name: " << name
<< ", Mid: " << midterm
<< ", Final: " << final << "\t"
<< "Homework: {";
while(cin >> x) {
std::cout << x << ", ";
}
cout << "}" << endl;
if(cin.fail()) {
cin.clear();
string f;
cin >> f;
cout << "Stream failed - next token: " << f << endl;
}
}
}
Output:
Name: p1, Mid: 90, Final: 91 Homework: {92, 93, 94, }
Stream failed - next token: 81
Name: 82, Mid: 83, Final: 84 Homework: {85,
Edit:
This seems to be a machine specific thing; in particular a Mac issue. I tried running the code on another Linux and Mac machine and it worked on the Linux machine but not on the Mac.
My question then is how is it possible that this code could be platform dependent.