为什么scanf()的这个code引起无限循环? [英] Why is scanf() causing infinite loop in this code?

查看:140
本文介绍了为什么scanf()的这个code引起无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的C程序刚刚在每个循环读取从标准输入一数字。如果用户输入一些NaN时,一个错误应该被打印到控制台和输入提示应该再次回归。上的0输入,该循环应该结束,给出正/负的值的数目应打印到控制台。这里的程序:

I've a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input prompt should return again. On input of "0", the loop should end and the number of given positive/negative values should be printed to the console. Here's the program:

#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;

    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}

我的问题是,在进入一些非数字(如A),这将导致无限循环写作 - >犯错......一遍又一遍。我想这是一个scanf()的问题,我知道这个功能可以通过一个更安全的一种来代替,但这个例子是对于初学者来说,只是知道大概的printf / scanf函数,如果其他和循环。

My problem is, that on entering some non-number (like "a"), this results in an infinite loop writing "-> Err..." over and over. I guess it's a scanf() issue and I know this function could be replace by a safer one, but this example is for beginners, knowing just about printf/scanf, if-else and loops.

我已经读了答案这个问题通过其他问题脱脂,但没有真正回答这个特定的问题。

I've already read the answers to this question and skimmed through other questions, but nothing really answer this specific problem.

推荐答案

scanf函数仅消耗相匹配的格式字符串,返回所消耗的字符数输入。不格式字符串匹配任何字符导致其停止扫描并离开无效字符仍然在缓冲区中。正如有人说,你仍然需要在继续之前刷新无效字符移出缓冲区。这是一个pretty肮脏的修复,但它会从输出删除有问题的字符。

scanf consumes only the input that matches the format string, returning the number of characters consumed. Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer. As others said, you still need to flush the invalid character out of the buffer before you proceed. This is a pretty dirty fix, but it will remove the offending characters from the output.

char c = '0';
if (scanf("%d", &number) == 0) {
  printf("Err. . .\n");
  do {
    c = getchar();
  }
  while (!isdigit(c));
  ungetc(c, stdin);
  //consume non-numeric chars from buffer
}

编辑:固定code删除一气呵成所有非数字字符。不会打印出多个犯错为每个非数字字符了。

edit: fixed the code to remove all non-numeric chars in one go. Won't print out multiple "Errs" for each non-numeric char anymore.

这里是scanf函数的pretty很好的概述。

Here is a pretty good overview of scanf.

这篇关于为什么scanf()的这个code引起无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆