Once cin
sees a type disagreement between the input data and the variables you're trying to read into, it enters a "fail" state. The conflicting variables won't be updated. Observe:
2010-02-27 22:54:27 ~/tmp/ $ cat ju3.cpp
#include <iostream>
using namespace std;
int main() {
int x = 0;
int y = 12345;
string s, a;
printf("cin good? %d, reading...\n", cin.good());
cin >> a >> x >> y >> s;
printf("a=%s, x=%d, y=%d, s=%s\n", a.c_str(), x, y, s.c_str());
printf("... read, cin good? %d\n", cin.good());
return 0;
}
2010-02-27 22:54:36 ~/tmp/ $ g++ ju3.cpp -o ju3
2010-02-27 22:54:56 ~/tmp/ $ echo 1 2 3 4 | ./ju3
cin good? 1, reading...
a=1, x=2, y=3, s=4
... read, cin good? 1
2010-02-27 22:55:05 ~/tmp/ $ echo a x y z | ./ju3
cin good? 1, reading...
a=a, x=0, y=12345, s=
... read, cin good? 0
There are two ways to avoid the problem you're seeing.
- The quick-and-dirty solution is to just check
cin.good()
instead of comparing the numbers to -1
.
- If you want
cin
to behave more robustly, read into string
s instead of int
s, and manually verify that they contain only numeric characters. You can then use stringstream
to easily convert the strings to numbers.