check input

closed account (48CM4iN6)
how can I check if the input is integer or lettters? The program asks to enter an integer. IF the input is letter , the program should prompt the user that it is an "invalid input"
Do you know the range of numbers you are using?
In a loop:
a. Read the input into a std::string
b. Try to convert the string to an integer (a std::istringstream is handy for this)
c. If the attempt is successful and entire input was consumed, exit the loop; use the number
d. Else emit an error message and repeat the loop.

Something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <sstream>

int main()
{
    int number ;

    while(true)
    {
        std::string input ;
        std::cout << "number? " && std::cin >> input ;
        std::istringstream stm(input) ;
        if( stm >> number && stm.eof() ) break ;
        else std::cerr << "invalid input. " ;
    }
    
    // use number
    std::cout << number << '\n' ;
}
Last edited on
One way to do it is what JLBorges suggested above.

Another way would be to check if cin is in an error state after the input.
You can do that with something like:
1
2
3
4
int input;
cin >> input;
if (!cin.good()) // if (!cin) should work too
    // Bad input, do something about it 

(of course, normally you would want to make that into a loop and until the user enters a valid value, but this is just to demonstrate)
Note that you'll have to use cin.clear(); to clear the error flags before you can use cin again.
Hi,

I'm just trying to make sure that my program doesn't infinite loop when the user enters a character. This is all contained in a while loop.

1
2
3
4
5
6
7
8
9
10
cin >> input;
        if ((cin.good())) 
        {
            break;
        }
        else 
        {
            cin.clear();
            cin >> input;
        }        


this doesn't work, not sure why. advice is appreciated
Last edited on
www.parashift.com/c++-faq-lite/input-output.html#faq-15.3
Thanks!
Topic archived. No new replies allowed.