我正在使用命令行将文本文件输入程序,该程序使用文件中的信息显示与该文本文件中的内容相符的其他值。
test.exe < input.txt(命令行)
文件看起来像这样:
2
abc 123
qwe 456
数字 2 告诉我程序必须读取多少东西。 (在代码中命名为 COUNT)
double number[MAXVALUE];
char name[MAXVALUE][MAXLENGTH];
for(i = 0; i < COUNT; i++)
{
scanf("%s %lf", name[i], &number[i]);
}
这是输入代码的样子。
现在,如果我将 3 作为 COUNT,程序将尝试读取 3 行并将第 3 行显示为乱码。 如果输入的值不存在,如何防止 scanf 运行?
我厌倦了 if(scanf(....) != 1)
但它似乎不起作用。
最佳答案
首先,避免调用未定义的行为 %lf
用于读取double
,而不是int
。
然后,scanf()
的返回值用于检查读取是否成功。
引自 N1570 7.21.6.4 scanf 函数,第 3 段:
The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
这是一个改进代码的例子:
double number[MAXVALUE];
char name[MAXNAME][MAXLENGTH];
for(i = 0; i < COUNT; i++)
{
if (scanf("%s %lf", name[i], &number[i]) != 2)
{
fputs("read error\n", stderr);
exit(1); /* stdlib.h should be included to use this */
}
}
关于c - 如果从文件中输入的值为空,scanf 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40681151/