【问题标题】:While loop go through irrespective of conditions in CWhile循环不考虑C中的条件
【发布时间】:2023-03-13 15:22:01
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <ctype.h>


int main(void){
    int corX = 0;

    do{
        printf("Please enter number X:\n");
        scanf("%d",&corX);
    } while(!(isdigit(corX) && corX>1 && corX<80));

    printf("You entered X as: %d\n",corX);
    return 0;
}

嗨!上面的代码应该检查输入的值是否为整数并适合范围。如果没有,程序应该再次询问。不幸的是,它不能以这种方式工作。无论我写什么,循环总是通过,结果我收到输入的数字数字和其他符号的 0。有人可以解释一下,我做错了什么吗?

【问题讨论】:

标签: c loops while-loop


【解决方案1】:

您的 while 条件似乎有问题。我重写了它,我得到了我认为你想要的行为(当输入小于 1 或大于 80 时请求输入)

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

int clean_stdin()
{
  while (getchar()!='\n');
  return 1;
}


int main(void){
    int corX = 0;

    do{
        printf("Please enter number X:\n");
        scanf("%d",&corX);
    } while( ( corX<1 || corX>80 ) && clean_stdin() );

    printf("You entered X as: %d\n",corX);
    return 0;
}

编辑:我没有足够仔细地检查我的初始帖子。根本不需要检查 isdigit,因为您已经在 scanf 中使用%d,我将它完全从 while 条件中删除。作为无限循环问题的快速解决方案,我添加了@Gangadhar 在他的评论中提到的这篇帖子How to scanf only integer and repeat reading if the user enter non numeric characters? 的公认答案中提到的clean_stdin() 函数,我建议阅读它(我也应该在发布之前完成)

【讨论】:

  • 非常感谢,它几乎可以工作了-但是为什么在写不是数字的符号的情况下,程序会陷入无限循环,一遍又一遍地询问“请输入数字X:”?跨度>
  • 此解决方案无效。 isdigit(corX) 检查 corX 是否在 ASCII 范围 '0'-'9' 中,这与corX 在以%d 格式输入数字时获得的 corX(0-9 整数)的值不同。这意味着isdigit(corX) always 返回 0,即 !isdigit(corX) always 在输入任何数字时返回非零值。scanf 应该像 scanf("%c",&amp;corX) .
  • @IgorPopov 我试图修改我的答案以希望改进它。我同意你的观点,我的回答并没有涵盖所有内容(可能仍然没有)
猜你喜欢
  • 2023-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2012-02-14
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多