Reading Lines From stdin, Handling Special Cases

We just learned how to read from stdin line by line and print the result; you probably had something similar to this written:

char buf[100];

while (fgets(buf, 100, stdin)) {
  printf("%s", buf);
}

This code will faithfully replicate the input to the output. Since fgets reads until either it sees '\n' or it hits the limit (99 characters in this example, leaving one position for the terminating 0), the resulting buf will have a '\n' in the end if fgets stopped because it was an end of the line, or something else if the line was longer than 99 characters.

To better understand how fgets works, and how to make sense of its result, let's work on one more exercise. Given an input like this:

short line
longer line won't fit in 15 characters
now empty line

non-empty line

use fgets with a buffer of size 15 and print each non-empty line in “angle brackets” < >, removing new line characters, to produce an output like this:

<short line>
<longer line won't fit in 15 characters>
<now empty line>
<non-empty line>

To do that, you will need to use strlen to get the length of the string, and then check if the last character of the string is '\n'. If it is, this string completes the line; you can replace '\n' with 0 to terminate the string right there. But if it's not '\n', don't print '>' because the current string will continue into the next fgets invocation.

Tracking all these options might get tricky! You will probably need some flags to track if a line has started or has finished.

Try writing the code to figure this out!

#include <stdio.h>
#include <string.h>

int main() {
  char buf[15]; /* use a buffer of size 15 for this exercise */
  while (fgets(buf, 15, stdin)) {
    /* your code here! */
  }
  return 0;
}
© Alexander Fenster (contact)