What does fgets do?

£可爱£侵袭症+ 提交于 2019-12-06 17:05:59

问题


It is not equal:

fgets (answer, 256, stdin);

if (strncmp(answer, "sta", 4) == 0)
  printf("omg, it's equal"); 

This code is:

fgets (answer, 4, stdin);

if (strncmp(answer, "sta", 4) == 0)
  printf("omg, it's equal"); 

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.


回答1:


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.

From the manpage:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. 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.



来源:https://stackoverflow.com/questions/13445441/what-does-fgets-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!