【问题标题】:C Trying to validate integerC试图验证整数
【发布时间】:2017-01-11 23:16:34
【问题描述】:

试图验证整数,但当输入错误的值类型时,出现第一个 printf 的无限循环。

int main(int argc, char *argv[]) {
int input;
do{
    int starCount;
    printf("Please enter a number:");
    scanf("%d",input);
    do{
        scanf("%d",&input);
    }while(isdigit(input));
    for(starCount=0; starCount<input; starCount++){
        printf("*");
    }
    printf("\n");       
}while(input>0);

return 0;

}

【问题讨论】:

  • 我建议阅读一些documentation for the function scanf,然后在心里模拟代码的执行,看看为什么它不起作用。
  • 1) 为什么在循环前调用scanf()? 2)您应该检查调用scanf()返回的值。
  • 您有两个scanf 电话是可疑的。他们中的第一个没有通过地址传递它的变量调用未定义的行为。我会从这些开始。
  • @Andrei Pak:您为什么要尝试将isdigit 应用于您的input,您希望它做什么?请解释您在isdigit 应用程序背后的想法。你是怎么想到这个主意的?
  • isdigit 检查字符是否为数字,将其应用于由 scanf 填写的 int 是没有意义的 - scanf 在处理输入字符串时会调用 isdigit

标签: c validation integer infinite-loop


【解决方案1】:

你的逻辑是错误的有两个原因:

  • 您在do..while 的末尾检查了input,但之前在for 循环中使用了它。
  • 绝对没有必要使用双do..while循环。

您的初始 scanf 也有另一个错误:

scanf("%d", input);  // <-- should be `&input`

对于您的需要,一个do..while 就足够了:

    int input;
    do{
        int starCount;
        printf("Please enter a number:");
        if( 1 != scanf("%d",&input) || input < 0 )   // <-- check return value of scanf and valid `input`
        {
            break;
        }
        for(starCount=0; starCount<input; starCount++){
            printf("*");
        }
        printf("\n");       
    }while(1);

请注意,您可以/应该使用scanf 的返回值并在for 循环之前检查input 是否有效。

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 2011-09-27
    • 2012-11-02
    • 2012-10-10
    • 1970-01-01
    • 2013-02-20
    • 2017-01-01
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多