Input Validation to make sure only number c++

安稳与你 提交于 2019-11-29 16:15:10
Mats Petersson

If you test if (!(cin >> arr[count])) ... instead - isdigit(arr[digit]) tests if the value of arr[digit] is the ASCII code of a digit [or possibly matches Japanese, Chinese or Arabic (that is, as an Arabic script typeface, not that it's a 0-9 like our "Arabic" ones) digit]. So if you type in 48 to 57, it will say it's OK, but if you type 6 or 345, it's complaining that it is not a digit...

Once you have discovered a non-digit, you will also need to either exit or clean out the input buffer from "garbage". cin.ignore(1000, '\n'); will read up to the next newline or a 1000 characters, whichever happens first. Could get annoying if someone has typed in a million digits, but otherwise, should solve the problem.

You will of course also need a loop to read the number again, until a valid number is entered.

The way I do this kind of input validation is that I use std::getline(std::cin, str) to get the whole line of input and then I parse it using the following code:

std::istringstream iss(str);
std::string word;

// Read a single "word" out of the input line.

if (! (iss >> word))
    return false;

// Following extraction of a character should fail
// because there should only be a single "word".

char ch;
if (iss >> ch)
    return false;

// Try to interpret the "word" as a number.

// Seek back to the start of stream.

iss.clear ();
iss.seekg (0);
assert (iss);

// Extract value.

long lval;
iss >> lval;

// The extraction should be successful and
// following extraction of a characters should fail.

result = !! iss && ! (iss >> ch);

// When the extraction was a success then result is true.

return result;

isdigit() applies to char not to int as you're trying. The cin >> arr[count]; statement already ensures an integer numeric digits format is given in the input. Check cin.good() (!cin respectively) for possible input parsing errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!