08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 ■ Characters

This problem is a bit more difficult than those we have met so far. When faced with such a

problem, it is best to tackle it a bit at a time, solving easier versions of the problem and working

your way up to solving the complete problem.

For this problem, we can first write a program that simply echoes the input without

numbering the lines. When we get this right, we can tackle the job of numbering the lines.

An outline of the algorithm for this first version is the following:

read a character, ch

while ch is not the end-of-file character

print ch

read a character, ch

endwhile

This will maintain the line structure of the data file since, for instance, when \n is read from

the file, it is immediately printed to the screen, forcing the current line to end.

Program P6.10 implements the above algorithm for reading the data from a file and printing

an exact copy on the screen.

Program P6.10

#include <stdio.h>

int main() {

char ch;

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

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

putchar(ch);

fclose(in);

}

Now that we can echo the input, we need only figure out how to print the line numbers.

A simplistic approach is based on the following outline:

set lineNo to 1

print lineNo

read a character, ch

while ch is not the end-of-file character

print ch

if ch is \n

add 1 to lineNo

print lineNo

endif

read a character, ch

endwhile

158

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!