Reputation: 2817
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?
Upvotes: 1
Views: 2175
Reputation: 4711
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.
cin.good()
instead of comparing the numbers to -1
. 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.Upvotes: 4
Reputation: 17119
input two strings and use functions in ctype.h
to check the validity of the input.
Upvotes: 0