c - 无法在循环内使用 fscanf() 输入元素

标签 c

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

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int N, M, i, a, b, k, total = 0;
    fscanf(stdin, "%d %d", &N, &M);
    fprintf(stdout, "N: %d, M: %d\n", N, M);

    for(i=0 ; i<M ; i++){
        fflush(stdin);
        fscanf(stdin, "%d, %d, %d", &a, &b, &k);
        fflush(stdout);
        fprintf(stdout, "A: %d, B: %d, K: %d\n", a, b, k);
        total += (((b-a)+1)*k);
        fprintf(stdout, "total: %d\n", total);
    }
    total = total/N;
    fprintf(stdout, "%d\n", total);
    return 0;
}

fscanf(stdin, "%d, %d, %d", &a, &b, &k);第一次执行,但之后就不再执行。而且即使是第一次,也只是变量 a 的值对于变量 b 是正确的,和k为零。尝试使用fflush(stdin) 在每次输入之前清除标准输入,但它不起作用。请帮忙。

[评论更新:] 不,我没有输入逗号。

最佳答案

fscanf(stdin, "%d, %d, %d", &a, &b, &k);

有格式字符串

"%d, %d, %d"

这意味着fscanf希望您输入一个数字,然后一个逗号,然后空格会丢弃任意数量的空白字符,包括没有(这是多余的%d 已经跳过它们),然后需要一个数字、逗号、任意数量的空白字符(包括无),然后是一个数字。

您输入三个数字,并用空格分隔。 fscanf 读取第一个数字,但无法扫描逗号。对 fscanf 的其余调用首先需要一个数字,但在 stdin 中发现了一个逗号,因此失败。

要修复它,请更改

fscanf(stdin, "%d, %d, %d", &a, &b, &k);

fscanf(stdin, "%d %d %d", &a, &b, &k);

或者

fscanf(stdin, "%d%d%d", &a, &b, &k);

关于c - 无法在循环内使用 fscanf() 输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524134/

相关文章:

sql - 简单的 C 库访问 MySQL

c - semclt 总是返回 -1

c - 为什么以及如何保护结构成员免受 C 中的直接操作

c - 如何从一美元.美分金额中分离出美分?

c - 将带空格的句子扫描到 C 中的 *char 数组中

c - 有关为 OO 语言编写编译器后端的资源?

c - 如何确定逻辑表达式中函数调用的顺序

经典 C. 在 execvp 函数、stdin 和 stdout 重定向中使用管道

C - 初始化指针数组

c++ - 指向 4 维数组的指针