0
votes

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.

1
That's correct, fget() reads the newline too (if there is room). That way, you know a complete line was read, not that the buffer was full. The program behaviour is undefined though, because fgets(s, 20, stdin) needs a buffer of size 20, not the 2 available in s[2].Weather Vane

1 Answers

0
votes

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