tags:

views:

116

answers:

2

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?

A: 

input two strings and use functions in ctype.h to check the validity of the input.

Yin Zhu
+4  A: 

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 strings instead of ints, and manually verify that they contain only numeric characters. You can then use stringstream to easily convert the strings to numbers.
Ben Karel
OK, so I'm using cin >> x >> y to read into strings instead of ints now, but how do I verify that the strings contain only numeric characters? the string class doesn't have an isdigit() function and looping over each letter in the string and trying to call isdigit() on that doesn't work either.
cornjuliox
Like Yin Zhu said, look at the ctype.h header (or the C++ equivalent, called cctype). You'll need to check each letter individually. If your code doesn't work the way you expect it to, use printf to find out why!
Ben Karel