If I were doing this, I'd do it somewhat differently. The usual way to read a line of input is to use fgets
. fgets
is fairly carefully written to support reading lines that are longer than the buffer you provided (and that support will work fine here).
To support long lines, fgets
leaves the entire line intact--including the new-line character that signals the end of the line. So, if it reads 81 characters, and no newline has been encountered yet, we know the line is over 80 characters long. Based on that, we can write code that seems (at least to me) to express our intent a little more closely:
static const int max = 82;
char buffer[max];
while (fgets(buffer, max, stdin)) {
if (strlen(buffer) > 80 && buffer[81] != '\n') {
fputs(buffer, stdout);
int ch;
while ('\n' != (ch=getchar()) && EOF != ch)
putchar(ch);
}
As it stands, this is marginally less efficient, since it re-scans through each line of input to find the string length. This is typically irrelevant (scanning is typically much faster than I/O), but if we really care about it, we can eliminate that as well.
To do that, we set the second to last character in the buffer to a new-line before calling fgets
. Then we look at (only) that character after the fgets
. If we read a line < 80 characters long, it will still contain the new-line we put there. If we read a line exactly 80 characters long, our new-line will be overwritten with an NUL terminator ('\0'). If the input line exceeds 80 characters, it will be overwritten with some other value (so then we print it out, and copy the remainder of the line as well).
printf("%s", line);
butline
is not null-terminated. \$\endgroup\$