#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/