How to trap integer inputs in C++?

This is just a portion of my program and I want to trap the integer inputs using while loop.

1
2
3
4
5
6
7
cout<<"\nEnter the name : ";
while(/*integer input or not in character*/)
{
   //Invalid Input!
}
cin.ignore();
cin.getline(name, 100);


Last edited on
Here's an example:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {

    string name;

    while (true) {

        bool ok = true;

        cout << "Enter your name:\n";

        getline(cin, name);

        size_t nameSize = name.size();

        if (nameSize == 0) continue;

        for (size_t i = 0; i < nameSize; ++ i) {
            if (
                !(
                    isalpha(name[i]) ||
                    name[i] == ' ' // || ...
                 )
               ) {
                ok = false; break;
            }
        }

        if (ok) break;
    }

    cout << "Hello, " << name << "!" << endl;

    return 0;
}

http://ideone.com/KuQgBL

Take a look at http://www.cplusplus.com/reference/cctype/
There several functions there that you may find useful.
Topic archived. No new replies allowed.