4.3 Character Sets and ASCII
A char stores one character, but internally it is represented by a small integer code. ASCII is a classic character set that assigns codes to common English letters, digits, punctuation, and control characters.
cpp
char letter = 'A';
std::cout << static_cast<int>(letter) << std::endl; // 65This numeric representation is why character comparisons work.
cpp
char ch = '7';
if (ch >= '0' && ch <= '9') {
std::cout << "digit" << std::endl;
}The characters '0' through '9' are consecutive in ASCII, as are 'A' through 'Z' and 'a' through 'z'.
C++ also provides helper functions in <cctype>:
cpp
#include <cctype>
if (std::isdigit(static_cast<unsigned char>(ch))) {
std::cout << "digit" << std::endl;
}
char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));The casts look a little noisy, but they keep <cctype> calls well-defined for every possible char value.
Loading interactive lab...
Loading concept check...
Loading practice...