only allow cin with specified input..

Hey all,

Happy Halloooooweeeeeeeen..

I want to restrict input on cin if i can. Say if the user needs to input a number 0-9 how can i capture just that and error trap anything else?

Say, the input is an integer but the user enters a float (ie 254.54) or a string or char, the program spins wildy out of control.

Is there any way to specify a range that cin with allow?

something like:
 
  cin.get(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)


I'm new to C++ so excuse my ignorance haha

i've tried:
1
2
3
4
while (!(cin >> OCTAVE))
{
    cout << "Bad Input";
}

...but it doesn't work as it i'd expect..

Paul..
To my knowledge there isn't a way to restrict the input, but you can certainly filter input and handle exception cases on your own! An easy way to fix your incoming input is to put it into a string first and then use formulas to determine if it fits your required model.

For instance, if I needed to verify that the incoming text was simply numerical:

1
2
3
4
5
6
7
bool isNumeric(const string& str){
    for(int a = 0; a < str.size(); a++){
        if (!isdigit(str[a]))
           return false;
    }
    return true;
}


http://www.cplusplus.com/reference/cctype/isdigit/

Obviously this function will not handle . or -
Last edited on
Hi,

Use std::stringstream.

http://www.cplusplus.com/reference/sstream/stringstream/stringstream/
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
http://en.cppreference.com/w/cpp/io/basic_ios/good


Have a look at the examples. You can use the good function to see if the last stream operation worked: if the input is bad this function returns false

The method of using isdigit isn't very good for floating point numbers like double, one has to account for +, -, e, E in the scientific format (+1.2e+3), as well as a host of error states like overflow, underflow etc.

Good Luck !!
Topic archived. No new replies allowed.