Warm tip: This article is reproduced from serverfault.com, please click

c-我可以使用fget从键盘读取多行吗?

(c - Can I read multiple lines from keyboard with fgets?)

发布于 2020-12-03 11:34:17

我想从C语言的stdin(我的键盘)中读取几行,但是我无法做到这一点。

我的输入看起来像这样:

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”甚至在读取我的新行char(以ASCII编码的10)。顺便说一句,我正在Linux终端中运行我的代码。

Questioner
Stefan Radulescu
Viewed
0
Krishna Kanth Yenumula 2020-12-03 20:37:20

我想从C语言的stdin(我的键盘)中读取几行,但是我无法做到这一点。

原因:

  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