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.
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, becausefgets(s, 20, stdin)
needs a buffer of size 20, not the 2 available ins[2]
. – Weather Vane