【问题标题】:Error check if user enters a letter or number错误检查用户是否输入字母或数字
【发布时间】:2016-02-10 19:09:10
【问题描述】:

我在检查字母时出错。如果输入了一个字母,那么它假设打印出错误并退出。如果它是一个数字,那么它应该在 if 下运行语句(我没有放入代码中,因为它目前无关紧要)。当我输入一个数字时,它应该运行 if 语句,但当我输入一个字母或数字时,它会转到 else 语句。

#include <stdio.h>
#include <ctype.h>


int main()
{
  int x;
  printf("Enter up to 10 positive integer ending with EOF:\n");

while((scanf("%d",&x)) != EOF && x < 100){


if( isdigit(x) ){
//statement
}

else{
printf("error, wrong input\n");
return 0;
}

}


if(x >= 100)
printf("error, wrong input\n");


return 0;
}

【问题讨论】:

  • C 编译器不关心缩进,但它让我很困惑。
  • 您无需与isdigit 核对。 scanf%d 已经检查输入是否可以解析为整数。并且还会在成功时将输入字符转换为整数。如果输入可以被解析为整数,它将返回1,否则返回0。那么你只需要检查if (x &gt;= 0 &amp;&amp; x &lt;= 9) 来做一个等效的isdigit 检查(虽然我怀疑你真的只是想检查输入是否是整数而不是数字)。

标签: c char letter error-checking


【解决方案1】:

你想让isdigit检查char,请将scanf改为:

while((scanf("%c",&x)) != EOF && x < 100){  // yes x is an int, but here you want a char

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2023-03-27
    • 2017-07-21
    • 2013-08-05
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多