以下代码在我编译后立即给出了奇怪的 o/p。
main() {
char name[3];
float price[3];
int pages[3], i;
printf ( "\nEnter names, prices and no. of pages of 3 books\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
scanf ("%c %f %d", &name[i], &price[i], &pages[i] );
printf ( "\nAnd this is what you entered\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}
但是如果我们在 %c 之前的 scanf 语句中给出空格,它会给出正确的 o/p。
谁能解释一下为什么会这样?
更新:-
如果我提供这样的输入-
F
123.45
56
J
134
67
K
145
98
那么我的问题是为什么我们不在 %f 之前和 %d 之前留出空间?为什么我们只需要在 %c 之前留出空间?
在格式字符串中添加空格使 scanf
能够从每次您按 return 时发生的输入中获取换行符。如果没有空格,name[i]
将收到字符 '\n'
,真正的 字符将被 误解>%f
.
那么,假设你的输入是
a 1.0 2
b 3.0 4
c 5.0 6
程序看起来更像这样:
a 1.0 2\nb 3.0 4\nc 5.0 6\n\377
也就是说,换行符是文件中的实际字符(此处的\377 表示“文件结束”)。
第一个 scanf
似乎工作正常,消耗一个字符、一个 float 和一个整数。但它留下这样的输入:
\nb 3.0 4\nc 5.0 6\n\377
所以第二个 scanf
将读取 '\n'
作为它的 %c,除非你先把它去掉。
将空格添加到格式字符串指示 scanf 丢弃任何空白字符(空格 ' '
、制表符 '\t'
或换行符 '\n'
).
A directive is one of the following:
A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
...
from http://linux.die.net/man/3/scanf
每当您在循环中将 scanf
与 %c
一起使用时,就会出现此类问题。因为,假设自由格式输入,换行符可以出现在任何地方。因此,通常使用双层 方法来尝试避免整个问题。您将 行 的输入读入缓冲区(使用 fgets
);砍掉愚蠢的换行符;然后使用 sscanf
而不是 scanf
从缓冲区(字符串)而不是直接从文件中读取。