Search code examples
cnumberscountergetcharputchar

printing line number in c using getchar and putchar


is there a way to print out the line number in C while only using putchar and getchar and no arrays?

the output should look like this. for example input mink

01: mink
02: jaguar 

and so on

The line number should go from 01 to 50.

This is my start approach

#include <stdio.h>

int main() {
    int c;
    int counter = 1;

    while ((c = getchar()) != EOF) {
        putchar(c);
        if (c == '\n') {
            putchar(counter + '0');
            putchar(':');
            putchar(' ');
            ++counter;
        }
    }
    return 0;
}

Solution

  • Assuming the line number is only 2 digits, compute and output these digits and the : prefix. To avoid duplicating code for the beginning of the file and to avoid printing a line number for the non-existing line after the end of the file, print the line number before the first character of each line, that is after the newline if there is another character. Initializing lastc to '\n' ensures a line number is printed before the first line of the file, if there is at least one line.

    Here is a simple imlementation:

    #include <stdio.h>
    
    int main() {
        int c, lastc = '\n';
        int counter = 1;
    
        while ((c = getchar()) != EOF) {
            if (lastc == '\n') {
                putchar('0' + counter / 10 % 10); // tenths digit
                putchar('0' + counter % 10);      // units digit
                putchar(':');
                putchar(' ');
                counter++;
            }
            putchar(c);
            lastc = c;
        }
        return 0;
    }