首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c、gets()、fgets()

c、gets()、fgets()
EN

Stack Overflow用户
提问于 2011-01-27 06:25:31
回答 3查看 607关注 0票数 2
代码语言:javascript
复制
char s1[100];
char s2[100];
gets(s1);
fgets(s2,sizeof(s2),stdin);
printf("%d,%d\n",strlen(s1),strlen(s2));

在运行之后,我输入了两次"abcd“,得到的结果是:4,5为什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-27 06:31:03

gets / fgets手册页:

代码语言:javascript
复制
 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时不可能防止缓冲区溢出。

票数 4
EN

Stack Overflow用户

发布于 2011-01-27 06:28:50

因为fgets返回的字符串末尾是'\n',而gets不是。

票数 2
EN

Stack Overflow用户

发布于 2011-01-27 06:29:38

gets() man page

gets()函数等同于具有无限nstream stdinfgets(),只是换行符(如果有的话)不会存储在字符串中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4810764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档