Reading from stdin
We learned how to read a file line by line, but we often want to read not from a file, but from standard input, as we did in earlier exercises. Luckily, the standard library defines a variable, FILE *stdin, which behaves like a file but actually reads from standard input.
So, to read one line from standard input with fgets, you can write
char buf[100];
fgets(buf, 100, stdin); /* will return NULL at the end of input */
Most of the standard library file functions have their stdin counterpart, e.g. getchar() is equivalent to fgetc(stdin), but for fgets, historically, there is no stdin-specific counterpart. There was a function called gets but it was unsafe because it did not accept the buffer size and could easily write beyond the boundary of the array, so it's deprecated and removed in newer versions of the language, and must not be used.
So, if you want to read a line from standard input, just use the same fgets that you would use for reading from file.
Now, let's have one more exercise. This time, you task would be to read the whole standard input line by line, using fgets with stdin, and print it to standard output, as is–just so you saw that it indeed works as I described!
Of course, you could just read the input character by character, as in while ((c = getchar()) != EOF), but please don't do it here, use fgets instead. To print strings back, you can use fprintf("%s", buf), or use the function puts which just prints a string: puts(buf).
#include <stdio.h>
int main() {
char buf[100];
/* TODO: copy standard input to standard output using fgets */
return 0;
}
Note that using printf(buf) is wrong! buf can contain formatting characters such as %d, so you must not let printf think that buf is a format string. The proper way to print a string with printf is printf("%s", buf).