Prevent entering age as characters

Hi, im just started learning c++, and this is just a part of the code of my own 'exercise'.

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
string name;
int age;
int choice;

    printf("Hi! What is your name? \n");
    getline(cin,name);
    system("cls");
    cout << "Hello " <<name << " !"<<endl;
    cout << "How old are you?\n";
    cin >> age;
    system("cls");


i would like to know how to prevent people from entering characters as the 'age' because that would cause a bug to happen.
Yep, you've discovered one of the weaknesses in the cin object. The best way around this is to read the user input as a string, and then convert it using atoi().
Thanks! That helped, but is there any way to deny and ask the user to input a valid integer?
Sure...test the return value of atoi, and if it didn't work right, ask the user again.

You can construct a simple loop for this in a number of ways.
can i use isdigit()?
I suppose so, but you'll have to check the chars one at a time. You'll still have to read the input into a string first, and iterate through it.
Topic archived. No new replies allowed.