Is trailing newline necessary in fgets?

可紊 提交于 2019-12-11 02:04:23

问题


When I search using keywords of 'fgets' and 'newline', there are many posts regarding how to remove the trailing newline character (and such removal appears to be a burden). Yet it seems there is few explaination on how that newline is necessary for fgets to include. Also in C++, the 'std::getline' and 'std::istream:getline' methods will not keep the newline character. So is there a reason for it?


回答1:


Here is satisfying (IMHO) explanation:
http://www.cplusplus.com/reference/cstdio/fgets/

Especially:

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.




回答2:


No, it's not necessary but if present it will be included in the returned line.

The manual page says:

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.

So that's why it behaves that way.

Note that you can't assume that there will be a newline last in the buffer, you must check before removing it otherwise you risk truncating the last line if it didn't have a newline.



来源:https://stackoverflow.com/questions/26672134/is-trailing-newline-necessary-in-fgets

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