c - For 循环跳过 scanf()

标签 c scanf

我正在尝试编写一个小程序,用户指定他们希望输入 n 个数字,然后系统会提示他们在后续行中输入 n 个 float 并提示。 预期的输出是

$./a.out
How many number (at least two)? > 4
Enter a number (3 more to enter) > 2
Enter a number (2 more to enter) > 3
Enter a number (1 more to enter) > 5
Enter a number (0 more to enter) > 7

但是,我的程序当前读取第一个输入(在我的示例中为 2),然后跳过其余提示的用户输入。

我当前代码的输出是

$./a.out
How many number (at least two)? > 4
Enter a number (3 more to enter) > 7
Enter a number (2 more to enter) > 
Enter a number (1 more to enter) > 
Enter a number (0 more to enter) >

我搜索了一个解决方案 here , here , 和 here ,但我什么也做不了。 有没有人对如何让 scanf 在这方面工作有任何建议? 我更喜欢使用 scanf,因为我们还没有介绍任何 gets 函数的用法。


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

main(){
    int i,n;
    int temp_count,count,rv;
    float number[10000];
    printf("How many number (at least two)? > ");
    rv = scanf("%d",&n);
    if(n<2||rv!=1){
        printf("Please enter at least two numbers");
    }
    count=n;
    for(i=0;i<n;i++){
        count--;
        printf("Enter a number (%d more to enter) > ",count);
        fflush(stdin);
        scanf(" %.2f",number[i]);
    }
    return(0);
}    //end main

最佳答案

作为用户@user3121023 发表评论(评论现已删除):

scanf("%f",&number[i]); ampersand needed. Do not fflush(stdin);

scanf() 的最后一个参数应该是指向将存储输入的缓冲区的指针。在您的例子中,number[i] 是一个float,而不是一个float *。在 number[i] 之前添加一个 & 会给 scanf() i 的地址:数组。

此外,在输入流上使用 fflush() 是一个坏主意,因为它会调用未定义的行为。它可能有效,但也可能无效。参见 here供引用 fflush()

注意:输入流上的 fflush()POSIX(非标准 C)明确定义,并且仅当流可搜索时。标准输入通常不可搜索。

关于c - For 循环跳过 scanf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384372/

相关文章:

c - 获取指针数据的大小

c - sscanf 在相同格式的输入上失败

c - 在 C 中使用指针的 Scanf

c - 如何在ubuntu上编译doom?

在 Visual Studio Code 中进行 C 编译

C: 如何让我的程序拒绝长度超过 'y' 或 'n' 的单词?

c - 使用 scanf 读取字符串作为输入

scanf时与char数组混淆

c - 如何强制将int的大小用于调试目的?

c - 使用 C 中的 YAJL 树检测 JSON 文件中的数组时出现问题