【问题标题】:Can I read multiple lines from keyboard with fgets?我可以使用 fgets 从键盘读取多行吗?
【发布时间】:2020-12-03 11:34:17
【问题描述】:

我正在尝试从 C 中的标准输入(我的键盘)读取几行,但我无法做到这一点。

我的输入是这样的:

3
first line
second line
third line

这是我的代码:

char input[2], s[200];
if (fgets(input, 2, stdin) != NULL) {
    printf("%d\n", input[0]);
    for (int i = 1; i <= input[0] - '0'; i++) {
        if (fgets(s, 20, stdin) != NULL)
            printf("%d\n", s[1]);
    }
}

这个函数,“fgets”似乎正在读取我的新行字符,用 ASCII 编码的 10。 顺便说一句,我在 linux 终端中运行我的代码。

【问题讨论】:

  • 没错,fget() 也会读取换行符(如果有空间)。这样,您就知道读取了完整的行,而不是缓冲区已满。但程序行为是未定义的,因为fgets(s, 20, stdin) 需要大小为 20 的缓冲区,而不是 s[2] 中可用的 2。

标签: c stdin fgets


【解决方案1】:

我正在尝试从 C 中的标准输入(我的键盘)读取几行,然后我 无法做到这一点。

原因:

  1. printf("%d\n", input[0]); 此语句打印一个额外的\nfgets 在第一次迭代期间读取。因此,s 将在第一次迭代中存储 \n。使用getchar() 阅读额外的\n

  2. fgets(s, 20, stdin),你正在读取 20 个字节,但是输入字符串(第二个)占用了 20 多个字节。增加它。

  3. printf("%d\n", s[1]);改为printf("%s\n", s);

代码是:

#include <stdio.h>
#include <string.h>

int main()
{

    char input[2], s[200];
    if (fgets(input, 2, stdin) != NULL)
    {
        printf("%d\n", (input[0]- '0'));
        getchar();  // to read that extra `\n`
        for (int i = 1; i <= (input[0] - '0'); i++)
        {
            if (fgets(s, 50, stdin) != NULL) // increase from 20 to 50
                printf("%s\n", s);  // printing string
        }
    }

    return 0;
}

输出是:

3
3
this is first line
this is first line

this is the second line
this is the second line

this is the third line
this is the third line

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多