scanf()在空输入时不失败,但什么都不做。您可能要检查返回值,如下所述:
人的fscanf
这些函数返回匹配成功并分配输入项目的 甚至为零的数量,它可以比规定少,或发生早期匹配 失败的事件。
The value EOF is returned if the end of input is reached before either the
first successful conversion or a matching failure occurs. EOF is also returned
if a read error occurs, in which case the error indicator for the stream
(see ferror(3)) is set, and errno is set indicate the error.
关于未初始化的我:这是与0的隐式初始化有人称之为一个特征。
但是,如果你有不到位的scanf()函数,编译器会提醒你:
#include <stdio.h>
int main()
{
int i, j;
scanf("%d", &i);
printf("%d/%d\n", i, j);
return 0;
}
编译所有启用了警告:
$ cc -Wall -Wextra -Wpedantic test.c -o test
test.c: In function 'main':
test.c:6:11: warning: 'j' is used uninitialized in this function [-Wuninitialized]
printf("%d/%d\n", i, j);
^
运行程序
$ ./test < empty_file
0/0
你看,甚至j打印出一个零。
我加入了另外一个测试:
int k = i;
int l = j;
printf("%d/%d\n", k, l);
结果:
$ ./test < empty_file
1115201808/0
所以,当我通过scanf函数跑,j是完全未初始化
新增scanf函数后。
结果可随意再现,k始终是随机的,l始终为零。
总是检查[scanf]的返回值(http://en.cppreference.com/w/c/io/fscanf),它告诉你转换是如何进行的。至于第二个问题;零*是垃圾值。 – user694733 2014-09-29 12:46:52
你的主要应该是: 'int main(int argc,char * argv [])' – Igor 2014-09-29 12:49:34
我用另一个变量来存储scanf的返回值并打印出来,并打印出0。因此它返回NULL? – Mutinifni 2014-09-29 13:01:26