为什么 `scanf` 表现得像这样?

huangapple go评论54阅读模式
英文:

Why is `scanf` behaving like this?

问题

这段代码的目的是要求用户输入,直到他们输入一个整数,但只有在用户在第一次迭代中输入整数时才有效。如果用户首先输入字符,然后输入整数,循环将继续迭代。

我找到的唯一解决方法是使用fflush(stdin),但它并不起作用。

英文:
#include <stdio.h>

int main(void)
{
    int i;
    while (1)
    {
        if (scanf("%i", &i) == 1)
        {
            break;
        }
        fflush(stdin);
    }
}

This code is supposed to ask the user for input until they input an integer, but it only works if the user inputs an integer in the first iteration. If the user first inputs a character, for example, then an integer, the loops continues iterating.

The only answer I have found to my problem said using fflush(stdin) should work, but it doesn't.

答案1

得分: 3

From C17:

如果流指向一个输出流或最近一次操作不是输入的更新流,则fflush函数会导致该流的任何未写入数据被传送到主机环境以写入文件;否则,行为是未定义的。

其中可能的未定义行为范围包括:

完全忽略情况,导致不可预测的结果,或在翻译或程序执行期间以环境特征的已记录方式行为(无论是否发出诊断消息),或终止翻译或执行(并发出诊断消息)。

在可移植方式下,不能对输入流使用fflush()。请参阅使用fflush(stdin)

更好的解决方案是使用fgets()读取整行,然后使用sscanf()strtol()等进行解析。

英文:

From C17:

> If stream points to an output stream or an update stream in which the
> most recent operation was not input, the fflush function causes any
> unwritten data for that stream to be delivered to the host environment
> to be written to the file; otherwise, the behavior is undefined.

where possible undefined behavior ranges from:

> ignoring the situation completely with
> unpredictable results, to behaving during translation or program
> execution in a documented manner characteristic of the environment
> (with or without the issuance of a diagnostic message), to terminating
> a translation or execution (with the issuance of a diagnostic
> message).

You can not use fflush() on an input stream in a portable manner. See Using fflush(stdin).

A better solution would be to read a whole line with fgets(), and then parse it with sscanf(), strtol(), et cetera.

huangapple
  • 本文由 发表于 2023年2月24日 02:01:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定