Functions for Characters in C

Let's explore, in this lesson, the functions for character handling in C Language.

We'll see how to use the scanf and printf functions to read or write characters. We'll introduce the getchar and putchar functions to read and write characters from/to console. Finally, we'll see some of the functions from the ctype.h library for character manipulation.

Reading and Writing characters with scanf and printf

The scanf and printf functions, already seen in action previously, allow reading and writing characters from/to console as well. To do this, it's sufficient to use the format specifier %c for reading and writing a single character.

For example:

char ch;

printf("Insert a character: ");
scanf("%c", &ch);

printf("You inserted the character: %c\n", ch);

The scanf function, however, does not skip spacing characters (such as spaces, tabs and line feeds) and considers them as valid characters.

To avoid this problem and force the reading of a single character skipping any spacing characters, we can add a space before the format specifier %c:

/* Reads a single character skipping any spacing characters */
scanf(" %c", &ch);

The fact that the scanf function does not skip spacing characters can be used to our advantage. In fact, it can be used to determine, for example, when a line feed character is inserted.

For example, we can use a do-while loop to read one character at a time until a line feed character is inserted:

char ch;

do {
    scanf("%c", &ch);
} while (ch != '\n');

To recap:

Definition

Format specifier %c for scanf and printf

The format specifier %c allows reading and writing a single character with the scanf and printf functions.

With the scanf function, if preceded by a space, it allows skipping any spacing characters:

scanf(" %c", &ch);

The getchar and putchar functions

The C standard library provides other ways to read and write characters from/to console. These methods are represented by the getchar and putchar functions.

The putchar function takes a character as input and prints it on console:

char ch = 'A';
putchar(ch);

The getchar function reads a single character from console and returns it as a return value:

char ch;

ch = getchar();

In truth, the getchar function returns an integer int instead of a char. We'll see why it does so in future lessons. For now let's take it as a given fact.

In any case, we can safely assign the value returned by the getchar function to a variable of type char.

Similarly to the scanf function, the getchar function does not skip spacing characters.

Definition

Function getchar

The getchar function reads a single character from console and returns it as a return value.

Its prototype is as follows:

int getchar(void);
Definition

Function putchar

The putchar function prints a single character on console.

Its prototype is as follows:

int putchar(int c);

The getchar and putchar functions are more performant compared to scanf and printf for reading and writing single characters. The reasons are two:

  1. First of all, they are simpler functions and therefore faster.

    The printf and scanf functions are very complex. They accept a format string as input precisely because they must be able to read and write data of different types. This makes them slower compared to getchar and putchar, which instead work only with characters.

  2. Secondly, getchar and putchar are often implemented as macros and not as functions, which makes them even faster. We'll study macros in upcoming lessons.

The getchar function also has another advantage compared to the scanf function.

The fact that it returns the read value, rather than storing it in a passed variable, allows writing more idiomatic code. In the sense that we can write more concise and readable code.

For example, let's take the example above where we used the scanf function to read one character at a time until a line feed character is inserted:

char ch;

do {
    scanf("%c", &ch);
} while (ch != '\n');

With the getchar function we can write the same code more concisely:

char ch;

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

In this example, the variable ch is initialized with the value returned by the getchar function. The while loop is executed as long as the value of ch is different from the line feed character. But the loop body is empty, because all the work is done by the loop condition.

We can also reduce the code further by avoiding the use of a temporary variable:

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

We can use similar code also to implement a loop that skips any spacing characters and returns the first non-spacing character:

char ch;

while ((ch = getchar()) == ' ' || ch == '\t' || ch == '\n');

When the loop terminates, the variable ch will contain the first non-spacing character.

Note

Be careful using getchar and scanf together

When using both getchar and scanf in the same program, attention must be paid.

The scanf function, in fact, tends to leave in the input characters that it has only read but not consumed. This can cause problems when switching from scanf to getchar.

Let's take an example. Suppose we write a portion of code that first reads an integer with scanf and then a character with getchar:

printf("Insert an integer: ");
scanf("%d", &n);
printf("Insert a character: ");
ch = getchar();

The first call to scanf reads an integer from keyboard and stops at the press of the Enter key. The problem is that the Enter key leaves a line feed character in the input buffer. The line feed character is not consumed.

Therefore, when the getchar function is called, it reads the line feed character left by scanf and not the character that the user inserted. This, obviously, is not the behavior we expect.

One possible solution is to use a loop, similar to those seen above, to consume any spacing characters and exit the loop only when a valid character is inserted:

printf("Insert an integer: ");
scanf("%d", &n);

printf("Insert a character: ");
do {
    ch = getchar();
} while (ch == ' ' || ch == '\t' || ch == '\n');

Functions for char

The C standard library provides a whole series of ready-made functions to work with characters. These functions are defined within the ctype.h library and are useful for performing comparison, conversion and manipulation operations on characters.

We'll see the complete list of these functions in upcoming lessons. In this lesson we'll see some of the most important ones.

Converting a character to uppercase or lowercase

To convert a character to uppercase or lowercase we can use the toupper() and tolower() functions respectively.

Let's see an example:

#include <stdio.h>
#include <ctype.h>

int main() {
    char c = 'a';
    char c_uppercase = toupper(c);
    printf("Initial character: %c\n", c);
    printf("Uppercase character: %c\n", c_uppercase);
    return 0;
}
Definition

Function toupper

The toupper function converts a lowercase character to uppercase. If the character passed as argument is already uppercase, the function will return the same character.

Its prototype is as follows:

#include <ctype.h>

int toupper(int c);
Definition

Function tolower

The tolower function converts an uppercase character to lowercase. If the character passed as argument is already lowercase, the function will return the same character.

Its prototype is as follows:

#include <ctype.h>

int tolower(int c);

Checking if a character is a letter or a number

To check if a character is a letter or a number we can use the isalpha() and isdigit() functions respectively.

Let's see an example:

#include <stdio.h>

int main() {
    char c;

    printf("Insert a character: ");
    scanf("%c", &c);

    if (isalpha(c)) {
        printf("The inserted character is a letter.\n");
    } else if (isdigit(c)) {
        printf("The inserted character is a number.\n");
    } else {
        printf("The inserted character is neither a letter nor a number.\n");
    }

    return 0;
}
Definition

Function isalpha

The isalpha function checks if the character passed as argument is a letter of the alphabet.

Its prototype is as follows:

#include <ctype.h>

int isalpha(int c);
Definition

Function isdigit

The isdigit function checks if the character passed as argument is a number.

Its prototype is as follows:

#include <ctype.h>

int isdigit(int c);

In Summary

In this lesson we saw how to manage characters through functions of the C standard library.

In particular:

  • We saw how to read and write characters with scanf and printf using the format specifier %c.
  • We introduced the getchar and putchar functions to read and write characters from/to console.
  • We saw how to convert a character to uppercase or lowercase with the toupper and tolower functions.
  • We saw how to check if a character is a letter or a number with the isalpha and isdigit functions.