使用 C isdigit 进行错误检查
在对 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;
}
While using the boolean check for the int num this loop doesn't work. The lines after it go unrecognized. Enter and integer like 60 and it just closes. Did I use isdigit wrong?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
isdigit(num)
时,num
必须具有字符的 ASCII 值(0..255 或 EOF)。如果它被定义为
int num
那么cin>>> num
将在其中放入数字的整数值,而不是字母的 ASCII 值。例如:
则
isdigit(num)
为 false(因为在 ASCII 的第 0 位不是数字),但isdigit(c)
为 true(因为在 ASCII 的第 30 位) ASCII 有一个数字“0”)。When you call
isdigit(num)
, thenum
must have the ASCII value of a character (0..255 or EOF).If it's defined as
int num
thencin >> num
will put the integer value of the number in it, not the ASCII value of the letter.For example:
then
isdigit(num)
is false (because at place 0 of ASCII is not a digit), butisdigit(c)
is true (because at place 30 of ASCII there's a digit '0').isdigit
仅检查指定字符是否为数字。一个字符,而不是两个字符,也不是一个整数,如num
的定义所示。您应该完全删除该检查,因为 cin 已经为您处理了验证。http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
isdigit
only checks if the specified character is a digit. One character, not two, and not an integer, asnum
appears to be defined as. You should remove that check entirely sincecin
already handles the validation for you.http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
如果您试图保护自己免受无效输入(超出范围、非数字等)的影响,则需要担心几个问题:
更多详细信息请参见此处:
忽略预期之外的用户输入选自
If you're trying to protect yourself from invalid input (outside a range, non-numbers, etc), there are several gotchas to worry about:
More detail here:
Ignore user input outside of what's to be chosen from