ASCII Value of a Character in C++
Find the ASCII code of any character in C++ by casting a char to int. Covers why A is 65, why the digit 0 is 48, and how ch - '0' turns a digit into a number.
1#include <iostream>2using namespace std;34int main() {5 char ch;67 cout << "Enter a character: ";8 cin >> ch;910 cout << "ASCII value of '" << ch << "' is: " << (int)ch << endl;1112 return 0;13}
Sample Output
ASCII value of 'A' is: 65
The character echoed in quotes, then its integer code.
In this one
- That a char is stored as a small integer code
- How (int)ch, int(ch), and static_cast<int>(ch) print that code
- Why cin >> ch skips spaces
- How to turn a digit character into its number
How it works
- 1
Declare char ch.
- 2
cin >> ch reads the first non-space character.
- 3
(int)ch converts the character to its numeric code.
- 4
cout prints the character in quotes and its code.
Edge cases
Typing a space
Press space then Enter.
cin >> ch skips whitespace, so it keeps waiting for a visible character. Use cin.get(ch) if you want to read a space (code 32).
Typing more than one character
Input: AB
Only A is stored and 65 is printed. B stays in the input buffer for a later read.
What's going on
This C++ program prints the ASCII code of a character by casting char to int. 'A' is 65.
char ch;
One character. Not a string.
cout << "Enter a character: ";
cin >> ch;
Skips whitespace. Type a space and it waits for a non-space character. Type AB and you only get 'A'. The B sits in the buffer.
(int)ch
That's the C-style cast. int(ch) is the same idea. static_cast<int>(ch) is the C++ spelling. All three print 65 for 'A'.
Sample: input A → ASCII value of 'A' is: 65.
Other useful codes:
'a' is 97 ('A' + 32)'0' is 48, not 0ch - '0'. '7' - '0' is 7.Letters, digits, and punctuation all have codes. That's the conversion. Unicode beyond a single byte is a different topic — this program is one char.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is '7' - '0'?
Pick an answer to check it.
Question 2
What does cout << 'A' + 1; print?
Pick an answer to check it.
Questions people ask
Why is 'a' 97 and 'A' 65?
ASCII puts uppercase letters at 65–90 and lowercase at 97–122. The gap is 32, so adding 32 turns an uppercase letter into lowercase.
What about characters like é or emoji?
Those are outside plain ASCII. In UTF-8 they take several bytes, so a single char cannot hold them.
Is there a difference between (int)ch and static_cast<int>(ch)?
For this case they give the same result. static_cast is the C++ style and is easier to search for in code.