char s1[100];
char s2[100];
gets(s1);
fgets(s2,sizeof(s2),stdin);
printf("%d,%d\n",strlen(s1),strlen(s2));在运行之后,我输入了两次"abcd“,得到的结果是:4,5为什么?
发布于 2011-01-27 06:31:03
从gets / fgets手册页:
The fgets() function reads at most one less than the number of characters
specified by n from the given stream and stores them in the string s.
Reading stops when a newline character is found, at end-of-file or error.
The newline, if any, is retained. If any characters are read and there
is no error, a `\0' character is appended to end the string.
The gets() function is equivalent to fgets() with an infinite n and a
stream of stdin, except that the newline character (if any) is not stored
in the string. It is the caller's responsibility to ensure that the
input line, if any, is sufficiently short to fit in the string.fgets保留换行符5,但gets不保留。另外,养成总是使用fgets的习惯,因为在使用gets时不可能防止缓冲区溢出。
发布于 2011-01-27 06:28:50
因为fgets返回的字符串末尾是'\n',而gets不是。
发布于 2011-01-27 06:29:38
从gets() man page
gets()函数等同于具有无限n和streamstdin的fgets(),只是换行符(如果有的话)不会存储在字符串中。
https://stackoverflow.com/questions/4810764
复制相似问题