c - 循环永远持续

标签 c loops while-loop scanf do-while

尽管在程序流程中出现了一个我不理解的令人沮丧的错误,但以下代码仍按预期编译和工作..
如果我传递 2 或 5 作为输入,主函数中间的循环工作正常。但是,当我传递 -3 或任何小于零的值(例如返回 -1 的字符)时,循环将永远持续下去,程序甚至不会暂停让我为 scanf 函数提供输入..

#include <stdio.h>
#include <stdlib.h>

void getNum(char * prompt, int*num)
{
    printf("%s", prompt);
    scanf("%d", num);
}

int main(int argc, char ** argv)
{
    int num = -1;
    while(num < 0) { // problem here
        getNum("Number of times you go to the gym in a week: ", &num);
    }
    return EXIT_SUCCESS;
}

我想知道错误是..

我注意到一些奇怪的事情..当我将循环更改为 do-while 循环时它工作得很好..

int main(int argc, char ** argv)
{
    int num;
    do {
        getNum("Number of times you go to the gym in a week: ", &num);
    } while (num < 0); // this works fine ..
    return EXIT_SUCCESS;
}

另外,出于某种原因,我重新编译了代码,它运行良好..

有人能解释一下吗?

最佳答案

接受答案后

scanf("%d", num);,在读取非数字输入时简单返回 0,单独保留 *num。有问题的文本仍在 stdin 中,后续调用将获得相同的文本和相同的结果。代码应检查 scanf() 结果值。

// weak
scanf("%d", num); // fails to consume offending input.

// good
*num = 0; // default answer
int retval;
do {
  printf("%s", prompt);
  retval = scanf("%d", num);  // returns EOF, 0, or 1
  // consume rest of line
  int c;
  while ((c = fgetc(stdin)) != '\n' && c != EOF);    
} while (retval == 0);  // repeat is no number read and stdin still open

[编辑]

避免使用 scanf()。报价How to test input is sane作为很好地处理读取 int 的解决方案。

关于c - 循环永远持续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180680/

相关文章:

java - While 循环因用户名/密码不匹配而退出

c - Scanf 更多值 C

c - 如何将 int 的值打印为 char?

java - 矩阵 : get value from given matrix

java - 循环减少数万,然后数千,然后数百,然后数十

c++ - 通过循环传递不同的数据类型

php - 3d嵌套数组foreach语句问题

javascript - JS 拆分变量

c - 指针如何获取变量、数组、指针、结构的地址

php - 我可以在php的if语句中运行while语句吗?