The char data type is used to store a single character. The literal value is stored within a set single quotes.
char letter = 'a';
char response = 'n';
char numCharacter = '6'; // the character 6, not numeric 6
Old style C strings were actually an array of chars, but now we have our own string data type.
Even when we store a number in a char, it is the char value, not the number you see that is stored.
The characters stored are stored as ASCII code which maps an 8-bit numeric value to a character.
To read data in, you perform the same type operations you would for any other data type.
char response = 'n';
cout << "Would you like to continue?";
cin >> response;
Escape Sequences
Sometimes we need to add a character to our output, or a string, that we simply cannot add. These are typically things like quotes (remember C++ doesn’t have multiple ways to enclose strings, just the double quotes), new line characters, tabs, etc.
C++ offers us an escaped sequence so we can specify these characters. By using a backslash and a special character, we can specify those special characters.
The endl is a special variable which stores the new line character, but requires us to exit from the string to add it. However, \n allows us to insert it into the string directly, without exiting from our first string.
Comparing and Testing Characters
Because the character is stored as a numeric value, you can test for greater than, less than, and all of the other comparison operators that is available to you.
if( response == 'y' )
{
// do some tasks
}
if ( letter >= 'a' && letter <= 'z' )
{
// the letter is lower case value
}
Character Functions
Within the <cctype>
header, C++ gives us several functions for working with characters.
isdigit(ch)
returns true if the character is a number.
isalpha(ch)
returns true if the character is a letter.
isalnum(ch)
returns true if the character is a letter or number.
isspace(ch)
returns true if the character is a white space character (tab, new line, etc)
islower(ch)
returns true if the character is a lower case character
isupper(ch)
returns true if the character is an uppercase character
tolower(ch)
returns the lower case character of the character that was passed to it.
toupper(ch)
returns the uppercase character of the character that was passed to it
Character Data Type and Operations in C++ was originally found on Access 2 Learn