Impose numeric limit on user input?

Hi, I'm working on an input/output tutorial Ii got from the cprogramming.com website, and I've been tinkering with it to get a better understanding of what I've learned so far. However, when a user enters anything other than a number, the program freaks out. So how do I keep a user from entering anything other than a number? Here is the code I have been using:


#include <iostream>

using namespace std;

int main()

{

int age, x = 0;

while ( x < 1 ) {

cout<< "Please input your age and press return: ";
cin>> age;
cin.ignore();

if ( age < 20 ) {
cout<< "You are just a baby! \n";
}

else if ( age >= 20 && age < 30 ) {
cout<< "You are pretty young! \n";
}

else if ( age >= 30 && age < 40 ) {
cout<< "You are REALLY old! \n";
}

else if ( age >= 40 ) {
cout<< "Wow, is GOD that old? \n";
}

cout<< endl;
}
}
Thanks for the help m4ster r0shi, reading that other thread helped, but i'm still having trouble. I only started learning C++ a couple of days ago, so looking at the other thread and trying to implement those solutions into my own code is difficult for me. Could you possibly show me how to do this in my own code? I know I'm asking for a lot, but it would really help me out.
Ok, I'll try to simplify the other example and explain more.

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
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int n;
    string str;
    bool entered_int;

    while (true)
    {
        entered_int=true;

        cout << "enter an int: ";
        cin >> n;

        if (!cin.good())
        {
            entered_int=false;
            cin.clear();
            getline(cin,str);
        }
        else
        {
            getline(cin,str);
            if (str!="") entered_int=false;
        }

        if (entered_int) break;
        else cout << "you did not enter an int..." << endl;
    }

    cout << "\n(hit enter to quit...)" << endl;
    cin.get();

    return 0;
}

The while statement above loops until you enter an integer.
Let's see how exactly it works by carefully studying some input cases...

Suppose we enter asdf. This causes the cin >> n; statement to alter
the internal state of cin so that cin.good() returns false,
and leaves the "asdf" string in the input buffer (meaning, it will be
the first thing encountered by the next input operation).

We have to do two things to rectify the situation:
(1) clear cin's internal state so that it can be used for input again (cin.clear();)
(2) remove the "asdf" string from the input buffer (getline(cin,str);)

At this point entered_int is false, so we keep looping.

Next, suppose we enter 123 asdf. Now, n is set to 123 and cin's state is unaltered
(cin.good() returns true), but we have a " asdf" string sitting in the buffer.
We don't want that. We remove it using getline(cin,str);, and then check
wether or not the string we got is empty. In this case it's not (it's " asdf"),
so, once more, entered_int is set to false and we keep looping.

Finally, we enter 123. n is set to 123, cin's state is unaffected and str is an empty string.
This means that entered_int is true, so we stop looping.
Last edited on
Again, thank you for your help M4ster r0shi. Your explanation really clarified that example for me, and i tried implementing it into my own code. It did keep my program from entering an infinite loop when a string was entered; however, whether or not the input is a string or integer, the program returns with both "You did not enter a valid age!" and "You are just a baby!" (the "You are just a baby!" is returned only in the case of the input being a string, or a number less than 20. If the number is greater than or equal to 20, then it returns "You did not enter a valid age!" and the appropriate response from my own code). Here is an example of what i mean:

Please input your age and press return: five
You did not enter a valid age!
You are just a baby!

Please input your age and press return: 20
You did not enter a valid age!
You are pretty young!

I guess i will just have to put this aside until i have a better understanding of C++, but thank you for your help!

Could you post your code?
Absolutely. I have tried several variations on this, including moving around your code to different places and even deleting pieces of my code that i felt were messing up the program. This i what i ended with, and seems to work the best except for the problems i described above:


#include <iostream>
#include <string>

using namespace std;

int main()

{

int age;
string str;
bool entered_int;

while ( true ) {

entered_int=true;

cout<< "Please input your age and press return: ";
cin>> age;

if ( !cin.good () ) {
entered_int=false;
cin.clear();
getline ( cin, str );
}

else {
getline( cin, str );
if ( str != " " ) entered_int=false;
}

if ( entered_int ) break;
else cout<< "You did not enter a valid age!" << endl;

if ( age < 20 ) {
cout<< "You are just a baby! \n";
}

else if ( age >= 20 && age < 30 ) {
cout<< "You are pretty young! \n";
}

else if ( age >= 30 && age < 40 ) {
cout<< "You are REALLY old! \n";
}

else if ( age >= 40 ) {
cout<< "Wow, is GOD that old? \n";
}
cout<< endl;

}
}
Some things:
1) You got a few useless conditions:
else if( age >= 20 && age < 30 )
for example - you already checked whether or not age was <20 before, so if you arrived at that point age is ALWAYS >=20. Same with the following ifs.

Your problem is basically just the position of your closing braces, specifically, there should be a } under
1
2
if ( entered_int ) break;
else cout<< "You did not enter a valid age!" << endl;


And use [ code ] ==>Your code goes here<== [ /code ] tags for your code, otherwise it's hard to read.
Last edited on
Ok, the problem here is that you don't wait for the user to enter a valid input for age before you operate on it.

Check this out:

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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int age;
    string str;
    bool entered_int;

    while (true)
    {
        //first, make sure we have a valid input for age...

        while (true)
        {
            entered_int=true;

            cout << "Please input your age (<=0 to quit) and press return: ";
            cin >> age;

            if (!cin.good())
            {
                entered_int=false;
                cin.clear();
                getline(cin,str);
            }
            else
            {
                getline( cin, str );

                //careful here, an empty string is "", not " "
                if (str!="") entered_int=false;
            }

            if (entered_int) break;
            else cout << "You did not enter a valid age!" << endl;
        }

        //then, operate on it...

        if (age<=0) break;

        if (age<20) cout<< "You are just a baby!";

        else if (age>=20 && age<30)
            cout << "You are pretty young!";

        else if (age>=30 && age<40)
            cout << "You are REALLY old!";

        else if (age>=40)
            cout << "Wow, is GOD that old?";

        cout << endl;
    }

    cout << "Bye!!! (hit enter to quit...)";
    cin.get();
}

HINT: [code]your code[/code] -> your code
Thank you so much M4ster r0shi! I get it now! I didn't realize that i needed another while loop inside the first to make sure i had a valid input for age. This definitely helped me out, and clarified a lot of things i was pretty fuzzy on. Oh, and reading your code has also taught me that i should put my opening braces on a new line rather than on the end of the previous line so i can see where i close them. Again, thank you for being patient and helping me out :D

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#include <iostream>
#include <string>

using namespace std;

int main()

{
    
    int age;
    string str;
    bool entered_int;
    
        while ( true ) 
        {
            
            while ( true )
            {
                entered_int=true;
            
                cout<< "Please input your age and press return: ";
                cin>> age;
            
                if ( !cin.good () ) 
                {
                    entered_int=false;
                    cin.clear();
                    getline ( cin, str );
                }
            
                else 
                {
                    getline( cin, str );
                    if ( str != "" ) entered_int=false;
                }
            
                if ( entered_int ) break;
                else cout<< "You did not enter a valid age! \n";
                cout<< endl;
            }
    
            if ( age < 20 ) 
            {
                cout<< "You are just a baby! \n";
            }
            
            else if ( age < 30 ) 
            {
                cout<< "You are pretty young! \n";
            }
            
            else if ( age < 40 ) 
            {
                cout<< "You are REALLY old! \n";
            }
            
            else if ( age >= 40 ) 
            {
                cout<< "Wow, is GOD that old? \n";
            }

            cout<< endl;
        }
}
Last edited on
Oh, and reading your code has also taught me that i should put my opening braces on a new line rather than on the end of the previous line

This is a matter of preference. If you like it, good for you, but it's not objectively better.
I know its a matter of preference, since i was putting my opening braces at the end of the previous line, but having the braces on their own lines makes it a lot easier and faster for me to see what brace im closing off.
Topic archived. No new replies allowed.