C++ Characters
The char type stores a single character, such as a letter, digit, or symbol. Characters are surprisingly interesting in C++ because behind the scenes they are stored as numbers, which opens up some clever tricks.
Declaring Characters
A char value is written between single quotes, like 'A' or '9' or '$'. This is different from a string, which uses double quotes and can hold many characters. A char always holds exactly one.
Working with chars
#include <iostream>
using namespace std;
int main() {
char grade = 'A';
char symbol = '#';
cout << "Grade: " << grade << endl;
cout << "Symbol: " << symbol;
return 0;
}Characters Are Numbers
Every character maps to a number through the ASCII table. For example 'A' is 65 and 'a' is 97. If you store a char in an int, or add a number to a char, C++ happily uses these numeric codes.
Seeing the ASCII value
#include <iostream>
using namespace std;
int main() {
char letter = 'A';
int code = letter; // 65
cout << letter << " = " << code << endl;
char next = letter + 1; // 'B'
cout << "Next letter: " << next;
return 0;
}Note: Remember to use single quotes for a char. Writing "A" with double quotes creates a string, not a char, and the two are not interchangeable.
- A char holds one character in single quotes.
- Each character has a numeric ASCII code.
- 'A' is 65, 'a' is 97, '0' is 48.
- Adding to a char shifts to the next character.