问题
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