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

To get around this problem, we must delay printing the line number until we are sure that

there is at least one character on the line. We will use an int variable writeLineNo, initially

set to 1. If we have a character to print and writeLineNo is 1, the line number is printed and

writeLineNo is set to 0. When writeLineNo is 0, all that happens is that the character just read is

printed.

When \n is printed to end a line of output, writeLineNo is set to 1. If it turns out that there is

a character to print on the next line, the line number will be printed first since writeLineNo is 1.

If there are no more characters to print, nothing further is printed; in particular, the line number

is not printed.

Program P6.12 contains all the details. When run, it will number the lines without printing an

extra line number.

Program P6.12

//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 = 0, writeLineNo = 1;

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

if (writeLineNo) {

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

writeLineNo = 0;

}

putchar(ch);

if (ch == '\n') writeLineNo = 1;

}

fclose(in);

}

We wrote the if condition as follows:

if (writeLineNo)...

If writeLineNo is 1 the condition evaluates to 1 and is, therefore, true; if it is 0, the condition is

false. We could also have written the condition as

if (writeLineNo == 1)...

In the statement

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

the expression ++lineNo means that lineNo is incremented first before being printed. By

comparison, if we had used lineNo++, then lineNo would be printed first and then incremented.

160

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!