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

Can I read multiple lines from keyboard with fgets?

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

I am trying to read a few lines from stdin (my keyboard) in C, and I wasn't able to do this.

My input it looks like this:

3
first line
second line
third line

There's my code:

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]);
    }
}

It seems that this function, "fgets" is reading even my new line char, coded with 10 in ASCII. BTW, I am running my code in linux terminal.

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

I am trying to read a few lines from stdin (my keyboard) in C, and I wasn't able to do this.

Reasons:

  1. printf("%d\n", input[0]); This statement prints an extra \n, which is read by fgets during first iteration. So, s will store \n in the first iteration. Use getchar() to read that extra \n.

  2. fgets(s, 20, stdin) , You are reading 20 bytes, but the input string (second one) occupies more than 20 bytes. Increase it.

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

The code is :

#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;
}

The output is :

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