08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6 ■ Characters

We have simply added the statements that deal with the line numbers to the algorithm above.

We can easily add the code that deals with the line numbers to Program P6.10 to get Program

P6.11. Note that when we print the line number, we do not terminate the line with \n since the

data must be written on the same line as the line number.

Program P6.11

//This program prints the data from a file numbering the lines

#include <stdio.h>

int main() {

char ch;

FILE *in = fopen("input.txt", "r");

int lineNo = 1;

printf("%2d. ", lineNo);

while ((ch = getc(in)) != EOF) {

putchar(ch);

if (ch == '\n') {

lineNo++;

printf("%2d. ", lineNo);

}

}

fclose(in);

}

Assume the input file contains the following:

There was a little girl

Who had a little curl

Right in the middle of her forehead

Program P6.11 will print this:

1. There was a little girl

2. Who had a little curl

3. Right in the middle of her forehead

4.

Almost, but not quite, correct! The little glitch is that we print an extra line number at the end.

To see why, look at the if statement. When \n of the third data line is read, 1 would be added to

lineNo, making it 4, which is printed by the next statement. This printing of an extra line number

also holds if the input file is empty, since line number 1 would be printed in this case, but there is

no such line.

159

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!