LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 858|回复: 2

should i put gets () before scanf()?

[复制链接]
发表于 2003-2-16 13:28:22 | 显示全部楼层 |阅读模式
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
main ()
{
char name[8];
char buf[1024];
int a,b;
printf ("input content:");
gets (buf);
printf ("input file name:");
scanf ("%s", name);
a = open (name, O_WRONLY);
write (a, buf,strlen(buf));
close (a);
}
a very funny thing:in the codes above,if i put scanf before gets(),just like:
.............
printf ("input file name:");
scanf ("%s", name);
printf ("input content:");
gets (buf);
............
after i compile it,the program will be quit automatically
who can tell me why?
sorry,there are some bugs with my xsim,so i had to type all in Eng
发表于 2003-2-17 10:25:37 | 显示全部楼层
是因为scanf和gets的字符结束标志的原因。
scanf先接受字符,它遇到最后一个输入的回车并不处理,直接返回它已经得到的字符串,而gets会直接得到那个scanf没有处理到的回车。

你可以做个测试,scanf读到空格也是会对回车一样的。而gets显然可以读到scanf时候输入的空格及接下来的字符。并将其存到文件里面。

假设你调换了两句的位置,先scanf然后gets
你按如下输入
[root@abcdefg test]# touch hi
[root@abcdefg test]# ./a.out
input file name:hi hihihi
input content:
[root@abcdefg test]#
[root@abcdefg test]# cat hi
hihihihi[root@abcdefg test]#
 楼主| 发表于 2003-2-17 10:31:27 | 显示全部楼层
9494,谢谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表