Not allow space in cin

How do I detect the user input to be a space and make them give me a numeric age? This doesn't work

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
41
42
43
44
45
46
47
  #include <iostream>
#include <string>

using namespace std;

int main()
{
    string name1, name2;
    int    age1 = 0, age2 = 0;
    int    dif  = 0;
    string ans;
    bool   stat = false;

    while (stat == false)
    {

        cout << "Hello, what is your name and age? (separate with one space) ";
        cin >> name1 >> age1;
        if (age1 == NULL)
            {
                cout << "Give me a real age! ";
                cin >> age1;
            }
        cout << name1 << ", what is your lover's name and age? ";
        cin >> name2 >> age2;
        if (age2 == NULL)
            {
                cout << "Give me a real age! ";
                cin >> age2;
            }
        cout << name1 << "'s age is " << age1 << " and " << name2 << "'s age is " << age2 << "." << endl
             << "Is this correct? (YES or NO)  ";
        cin >> ans;
        if (ans == "yes" || ans == "YES")
            stat = true;
        else
            {
                cout << endl << "Okay, let's try that again!" << endl << endl;
                stat = false;
            }
    }
    cout << endl << "This message means stat is true!";


    return 0;
}
1
2
3
4
5
6
7
8
9
#include <limits>
...
cout << "Hello, what is your name and age? (separate with one space) ";
cin >> name1;
while (!(cin >>  age1)) {
    cout << "Give me a real age! ";
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


The `>>` istream operator ignores any whitespace automatically so checking for this doesn't really make any sense because it will never read it
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

If you want to know how the while loop works:
http://www.cplusplus.com/reference/ios/ios/operator_bool/

It basically keeps looping until it reads a number. Each time it fails, it will ignore everything on the current line until the next line and clear any error flags
Last edited on
Topic archived. No new replies allowed.