c - 将 float 输入读取为 int 并无限循环

标签 c scanf

我正在尝试处理人为错误,如果我输入不正确的输入(例如浮点值),程序会再次提示输入。

我通过检查 scanf 是否未返回扫描的输入的正确数量(此处为 3)来做到这一点,然后它会再次询问。

但是,如果输入“5.4(float) 3 2”或“4 5.4(float) 3”作为输入,则得到无限循环,如果给出“5 4 3.2”作为输入,则获取 int 值。

我想知道为什么会发生这种情况。

我知道一些解决方法,例如使用多个 scanf。但我想知道原因。 这是我的代码:

#include <stdio.h>
int main(){
    int a,b,c,largest,error;
    do{
       printf("Enter three numbers to find largest:");
       error = scanf("%d %d %d",&a,&b,&c);
    }while(error != 3);
}

最佳答案

"5.4 3 2""4 5.4 3" 是相对简单的顶部句柄,因为当一个 '.' 时被 scanf() 使用时,它立即得知一定有问题。

但是,"4 3 5.4" 并不是那么微不足道。 scanf()消耗"4 3 5"后,返回3表示扫描成功3个整数,留下".4" 标准输入。因此,scanf() 的返回值不足以满足这种情况。

这是我的代码:

#include <stdio.h>

int main(void)
{
    int a, b, c, error;
    do
    {
        printf("Enter three numbers to find largest:");
        error = scanf(" %d %d %d", &a, &b, &c);
        if (getchar() != '\n')
        {
            error = 0;
            scanf("%*[^\n]");
        }
    }
    while(error != 3);
    return 0;
}

scanf("%*[^\n]"); 用于丢弃 stdin 中的所有字符,直到 '\n'。 "%d %d %d" 开头的空格告诉 scanf() 丢弃一个或多个空白字符(包括 ' '、'\n' 和 '\t ') 直到遇到第一个非空白字符。

<小时/>

事实上,您甚至不必检查 scanf() 的返回值:

#include <stdio.h>

int main(void)
{
    int a, b, c;
    for(;;)
    {
        printf("Enter three numbers to find largest:");
        scanf(" %d %d %d", &a, &b, &c);
        if (getchar() == '\n')
        {
            break; // successful
        }
        scanf("%*[^\n]");
    }
    return 0;
}

关于c - 将 float 输入读取为 int 并无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502547/

相关文章:

objective-c - Objective-C 代码可以调用 C 代码吗?反之亦然? (混合搭配它们)

c - 为什么我的程序在调试时崩溃了?

c - 如何判断输入是否结束?

c - scanf:浮点格式未链接

c - 简单的C scanf 不起作用?

C: 如何在编译内核模块时手动添加依赖

c - 执行 fgets/fputs 时最后一行重复

c - 将不同的单词保存到链接列表中

c - 使用C语言中的套接字向FTP服务器发送命令

c++ - 使用 fscanf 从文件中读取字符