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.
I am trying to read a few lines from stdin (my keyboard) in C, and I wasn't able to do this.
Reasons:
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
.
fgets(s, 20, stdin)
, You are reading 20 bytes, but the input string (second one) occupies more than 20 bytes. Increase it.
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