Using C isdigit for error checking

流过昼夜 提交于 2019-12-06 14:17:15
littleadv

When you call isdigit(num), the num must have the ASCII value of a character (0..255 or EOF).

If it's defined as int num then cin >> num will put the integer value of the number in it, not the ASCII value of the letter.

For example:

int num;
char c;
cin >> num; // input is "0"
cin >> c; // input is "0"

then isdigit(num) is false (because at place 0 of ASCII is not a digit), but isdigit(c) is true (because at place 30 of ASCII there's a digit '0').

isdigit only checks if the specified character is a digit. One character, not two, and not an integer, as num appears to be defined as. You should remove that check entirely since cin already handles the validation for you.

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

Tim

If you're trying to protect yourself from invalid input (outside a range, non-numbers, etc), there are several gotchas to worry about:

// user types "foo" and then "bar" when prompted for input
int num;
std::cin >> num;  // nothing is extracted from cin, because "foo" is not a number
std::string str;
std::cint >> str;  // extracts "foo" -- not "bar", (the previous extraction failed)

More detail here: Ignore user input outside of what's to be chosen from

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