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.

6.6.1 Count Characters in a Line

Chapter 6 ■ Characters

Suppose we want to count the number of characters in a line of input. Now we must read

characters until the end of the line. How does our program test for end-of-line? Recall that when

the “Enter” or “Return” key is pressed by the user, the newline character, \n, is returned by

getchar. The following while condition reads a character and tests for \n.

while ((ch = getchar()) != '\n')

Program P6.6 reads a line of input and counts the number of characters in it, not counting the

“end-of-line” character.

Program P6.6

//count the number of characters in the input line

#include <stdio.h>

int main() {

char ch;

int numChars = 0;

printf("Type some data and press 'Enter' \n");

while ((ch = getchar()) != '\n') // repeat as long as ch is not \n

numChars++;

// add 1 to numChars

}

printf("The number of characters is %d \n", numChars);

The main difference between this and Program P6.5 is that this one reads characters until the end

of the line rather than until the first non-blank. A sample run is:

Type some data and press 'Enter'

One moment in time

The number of characters is 18

6.7 Count Blanks in a Line of Data

Suppose we want to count all the blanks in a line of data. We must still read characters until

the end of the line is encountered. But now, for each character read, we must check whether

it is a blank. If it is, the count is incremented. We would need two counters—one to count the

153

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!