关于C#:在fgets中是否需要尾随换行符?

Is trailing newline necessary in fgets?

当我使用'fgets'和'newline'关键字进行搜索时,有很多关于如何删除结尾的换行符的帖子(这种删除似乎很麻烦)。 但是,似乎几乎没有什么解释可以包括fgets的换行符。 同样在C ++中," std :: getline"和" std :: istream:getline"方法将不保留换行符。 那有什么理由吗?


这是令人满意的(IMHO)说明:
http://www.cplusplus.com/reference/cstdio/fgets/

特别:

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.


不,不是必须的,但是如果存在,它将包含在返回的行中。

手册页显示:

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.

所以这就是为什么它会这样。

请注意,您不能假定缓冲区中的最后一行将有换行符,因此必须在删除之前进行检查,否则,如果没有换行符,则可能会截断最后一行。