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.

6.5 Read and Print Characters

Chapter 6 ■ Characters

Many programs revolve around the idea of reading and writing one character at a time, and

developing the skill of writing such programs is a very important aspect of programming. We can

use scanf to read a single character from the standard input (the keyboard) into a char variable

(ch, say) with:

scanf("%c", &ch);

The next character in the data is stored in ch. It is very important to note a big difference

between reading a number and reading a character. When reading a number, scanf will skip

over any amount of whitespace until it finds the number. When reading a character, the very next

character (whatever it is, even if it’s a space) is stored in the variable.

While we can use scanf, reading a character is important enough that C provides a special

function getchar for reading characters from the standard input. (Strictly speaking, getchar is

what’s called a macro, but the distinction is not important for our purposes.) For the most part,

we can think that getchar returns the next character in the data. However, it actually returns the

numeric code of the next character. For this reason, it is usually assigned to an int variable, as in:

int c = getchar(); // the brackets are required

But it can also be assigned to a char variable, as in:

char ch = getchar(); // the brackets are required

To be precise, getchar returns the next byte in the data – to all intents and purposes, this is

the next character. If we call getchar when there is no more data, it returns -1.

To be more precise, it returns the value designated by the symbolic constant EOF (all uppercase)

defined in stdio.h. This value is usually, though not always, -1. The actual value is system dependent,

but EOF will always denote the value returned on the system on which the program is run. We can,

of course, always find out what value is returned by printing EOF, thus:

printf("Value of EOF is %d \n", EOF);

For an example, consider the statement:

char ch = getchar();

Hello

Suppose the data typed by the user is this:

When ch = getchar() is executed, the first character H is read and stored in ch. We can

then use ch in whatever way we like. Suppose we just want to print the first character read. We

could use:

printf("%c \n", ch);

145

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!