fgets是做什么的? [英] What does fgets do?
问题描述
不相等:
fgets (answer, 256, stdin);
if (strncmp(answer, "sta", 4) == 0)
printf("omg, it's equal");
此代码是:
fgets (answer, 4, stdin);
if (strncmp(answer, "sta", 4) == 0)
printf("omg, it's equal");
为什么?这是因为在第一个答案中,我猜第4个位没有\ 0(如果我将其更改为3而不是4则可以).但是,fgets的作用是什么?字符串答案中的第一个是str \whitespace*253\0"
吗?第二个是str\0
?谢谢.
Why? It is because in the first, answer doesn't have \0 at the 4th place I guess (if I change it to 3 instead of 4 it works). But what does fgets do? String answer in the first is str \whitespace*253\0"
? And in the second it is str\0
? Thank you.
推荐答案
fgets
(与gets
不同)包括尾随的\n
,该末尾的\n
对应于在行末按回车键.如果将3
作为限制,它将截断字符串,并丢弃\n
.
fgets
(unlike gets
) includes the trailing \n
corresponding to the return pressed at the end of the line. If you put 3
as the limit it truncates the string, discarding the \n
.
从联机帮助页:
fgets()
从流中读取的字符数最多小于大小字符 将它们存储到s
指向的缓冲区中.读取后停止 EOF或换行符.如果读取了换行符,则将其存储到缓冲区中. 终止空字节('\0'
)存储在的最后一个字符之后 缓冲区.
fgets()
reads in at most one less than size characters from stream and stores them into the buffer pointed to bys
. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0'
) is stored after the last character in the buffer.
这篇关于fgets是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!