I've got the following piece of code:
...
int 开发者_运维技巧x = 0;
int y = 0;
cin >> x >> y;
if (x == -1 && y == -1) {
cout << "exit!";
}
else {
doSomething();
}
...
And it works, but only if I enter 2 numbers. If I were to enter a letter, like 'n', the program gets thrown into an infinite loop. How do I check to make sure the user entered a number and avoid the infinite loop?
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 intostring
s instead ofint
s, and manually verify that they contain only numeric characters. You can then usestringstream
to easily convert the strings to numbers.
input two strings and use functions in ctype.h
to check the validity of the input.
精彩评论