有关换行和fgets()的查询 [英] query regarding line feed and fgets()

查看:113
本文介绍了有关换行和fgets()的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码1:-

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

输出:-

ab cd
ab cd
(line feed)

代码2:-

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

输出:-

ab cd
ab cd

当我输入ab(space)cd(enter key)时,在fgets()的情况下,我的输出是line feed,而在gets()的情况下,则不会显示新的换行符. 在这种情况下,line feed有什么问题.

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.

推荐答案

gets() fgets() 在提供的缓冲区中读取FILE,直到检测到换行为止.前者存储换行的NUL ,后者存储换行的NUL 之后.

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.

请注意,gets()不安全,因为它没有提供任何方法来保护超出传递的缓冲区限制的写入.

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

fgets()占用缓冲区的大小,如果达到该大小,则停止读取.在后一种情况下, 读取之前可能会停止读取.

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.

对于在缓冲区末尾切掉各种换行符的一般方法,您可能想看看以下答案:https://stackoverflow.com/a/16000784/694576

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

这篇关于有关换行和fgets()的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆