Help please? How would I go about confirming that the user entered a number?

So, I've been trying to figure it out for a while but I can't seem to find an answer. If I was trying to find the age of a person, say with cin, is there any way I could confirm that the input is in fact a number? If I declare age as int it bugs out when a person types in something that isn't a number, but if I put string it obviously opens age up to not being a number.

Is it possible to compare ints and strings, for example, or manipulate strings in some way to check if the string is a number?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
cout<< "How about your age? \n";
          cin>> answers.age;
          bool ageCharValid = false;
          int ageValid = 0;
          bool ageGood = false;
          while (ageGood == false) {
                for (int y = 0; y > answers.age.length(); y++) {
                    for (int x = 0; x > 9; x++) {
                    if (answers.age[y] == x) {
                       ageCharValid = true;
                    }
                    if (ageCharValid == true) {
                       ageValid++;
                    }
                ageCharValid = false;
                }
                if (ageValid == answers.age.length()) {
                       ageGood = true;      
                }
                else {
                     cout<< "Sorry, that isn't an age. Try putting in numbers only.";
                }
          ageValid = 0;
          ageCharValid = false;
          }
          ageGood = false;


That's currently what I'm trying but it's not working on account of me comparing a string to an int, among other things most likely.
Last edited on
From this thread:
http://www.cplusplus.com/forum/general/116178/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <limits>
#include <iostream>

int main(int argc, char* argv[]) {

	unsigned short value = 0;
	while(1) {
		std::cout << "Enter value: ";
		if(std::cin >> value) {//if std::cin can read into value successfully without raising any error flags...
			break;//break out of the loop, because the user entered valid input
		}
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cout << "You entered : " << value << std::endl;

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	std::cin.get();
	return 0;
}
Last edited on
Thanks! That worked and now I know I can just use an if statement for that XD I was expecting it to bug out whenever I tried to compare anything not numeric to an int.
Topic archived. No new replies allowed.