input data type
I am trying to verify user input using <cctype>'s isdigit function. As I understand it's use, you pass a char and expect 0 or a non 0 (false/true) return.
Assume the user enters more than one character. I am looking for the best way to ignore everything after the first char. I have been reading about clear and flush and on and on. I am trying to figure out what, if any, is the best way to handle ...for lack of better term... dumb input from the keyboard... There seem to be so many opinions and suggestions, I would like some clarity, perhaps a comparison of different ways to handle input? or maybe a term to google...
thanks : )
There are two god ways. First, you can use getline to read a line of input into a string, and then ignore the rest of the string.
The second is to read into a char variable using cin >> and then call cin.ignore(<some big number>, '\n'). The <some big number> can be 100 or 1000 or something, but then it won't work if they type 101 or 1001 characters. It can also be std::numeric_limits<std::streamsize>::max(), but then you have to #include <limits> and I think maybe <ios>, and some people don't like to use things they've never heard of before.
If you're sure you only want a single digit (0-9), then either option is good. If you want to accept larger or negative numbers, then you'd have to adjust either one you use.
If using getline, then use a stringstream to grab the integer from the string you read in. If using cin >>, then read into an int variable, but do it in a loop like this:
while (!(cin >> my_int_variable))
// prompt again here if you want.
Ty for the info.
I am working on a tic-tac-toe game, 1-9 to play the board, 0 to quit. So for that it should never need more options.
It would seem for me reading a char would be best because I immediately isdigit(input). As far as numeric_limits, I think that a better way than just guessing at how long the cat may stand on the keyboard before stepping on enter. Will soon see how it works out for me, thanks.
Yes, it returns the biggest possible number an int can hold, and since ignore accepts an int, it makes sure you can skip as much of the buffer as possible.
Originally Posted by QuestionKing