使用C数字进行错误检查
Using C isdigit for error checking
对int num使用布尔检查时,此循环不起作用。后面的行无法识别。输入一个像60这样的整数,它就关闭了。我用错了isdigit吗?
int main()
{
int num;
int loop = -1;
while (loop ==-1)
{
cin >> num;
int ctemp = (num-32) * 5 / 9;
int ftemp = num*9/5 + 32;
if (!isdigit(num)) {
exit(0); // if user enters decimals or letters program closes
}
cout << num << "°F = " << ctemp << "°C" << endl;
cout << num << "°C = " << ftemp << "°F" << endl;
if (num == 1) {
cout << "this is a seperate condition";
} else {
continue; //must not end loop
}
loop = -1;
}
return 0;
}
调用isdigit(num)
时,num
必须具有字符的ASCII值(0..255或EOF(。
如果它被定义为int num
,那么cin >> num
将在其中放入数字的整数值,而不是字母的ASCII值。
例如:
int num;
char c;
cin >> num; // input is "0"
cin >> c; // input is "0"
则isdigit(num)
为假(因为ASCII的第0位不是数字(,但isdigit(c)
为真(因为ASCII第30位有数字"0"(。
isdigit
仅检查指定字符是否为数字。一个字符,而不是两个字符,也不是整数,因为num
似乎被定义为。由于cin
已经为您处理验证,因此您应该完全删除该检查。
http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
如果你试图保护自己免受无效输入(范围外、非数字等(的影响,有几个问题需要担心:
// 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)
此处提供更多详细信息:忽略用户输入之外的内容';s从中选择
相关文章:
- C++中的输入限制和错误检查
- 在错误检查非 int 的内容时,控制台被淹没
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- NPP 和 CUDA 错误检查
- 在此程序中获取错误:检查两个数组是否相等
- 错误 ~ 检查字符是否为小写字母
- 同时循环到错误检查 C++
- clang format函数和错误检查在同一行
- 使用宏进行赋值和错误检查
- 在C++中将命令行字符参数解析为int并进行错误检查
- 使用 Makefiles 在 Eclipse CDT 中进行错误检查
- 数据文件处理中的错误检查是否可以打开文件 - 为什么会发生
- 通过错误检查将参数转换为整数
- 这种错误检查方法的性能会不会太高
- C++通过错误检查将sscanf代码改编为distingstream
- 在windows错误检查中使用c++向gmail帐户发送电子邮件
- C++ 卷曲文件下载 - 错误检查
- 通过错误检查将 wstring 转换为双精度的方法
- 如何使用标准库函数通过错误检查将字符串 (char*) 转换为数字