query regarding line feed and fgets()

一世执手 提交于 2019-12-12 01:32:38

问题


Code 1:-

int main()
{
    char str[200];
    fgets(str,200,stdin);
    printf("%s",str);
    return 0;
}

Output:-

ab cd
ab cd
(line feed)

Code 2:-

int main()
{
    char str[200];
    gets(str);
    printf("%s",str);
    return 0;
}

Output:-

ab cd
ab cd

When I enter ab(space)cd(enter key) , then in case of fgets() I am getting a line feed in the output, whereas in case of gets(), no new line feed is displayed.
What is the matter of the line feed in this case.


回答1:


gets() and fgets() read for a FILE in to the buffer provided until a new-line is detected. The former stores a NUL instead of the new-line, the latter places the NUL after the new-line.

Please note that gets() is unsafe, as it does not provide any way to protect writing beyond the limits of the buffer passed.

fgets() takes the size of the buffer, and stops reading if this size is reached. In this latter case reading might stop before any new-line had been read.

For a general method of chopping of the various kinds of new-lines at the end of a buffer you might like to take a look at this answer: https://stackoverflow.com/a/16000784/694576



来源:https://stackoverflow.com/questions/22125410/query-regarding-line-feed-and-fgets

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