Entering valid user input!

Entering valid user input?



Hello guys; I am wondering if you can help me.
How can I write my simple program so if the user enters an invalid number,
The program won’t exit? I know I am supposed to use a if (cin) or if (!cin),
But I don’t know where in the program or how I should use it. Right now my
Program looks kind of like this:
If (number > 1 && number < 1001)
Go through some function loops
Else
Cout << “invalid number”;
I need to write it so when the user enters an invalid number, the program
Would Keep asking for the right number until it's given.
Thanks guys.
You could use some thing as explicit as this:
1
2
3
4
5
do
{
//other code and warnings go here

}while(number<1 && number>1000);
1
2
3
4
5
6
7
8
9
10
11
if(cin.good())
{
//
//
}
else
{
cin.ignore();
cin.clear();
cout << "Invalid input!\n";
}

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
#include <iostream>
#include <string>
#include <limits>

int getNum( const std::string& prompt,  int min, int max )
{
    int input ;

    std::cout << prompt << "\n> " ;

    while ( !(std::cin >> input)  ||  (input < min || input > max) )
    {
        // clear error state and remove rest of the line.
        std::cin.clear() ; 
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') ;

        std::cout << "Invalid input!\n" << prompt << "\n> " ;
    }
   

    return input ;
}


int main()
{
    int num = getNum("Enter a number between 10 and 100", 10, 100) ;
    std::cout << "You entered " << num << "!\n" ;
}
Topic archived. No new replies allowed.