ASCII Value of a Character in C++

Print the ASCII value of a character in C++ by casting char to int. 'A' is 65.

BeginnerBasic ProgramsExample 8 of 14
ascii-value-of-a-character.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 char ch;
6
7 cout << "Enter a character: ";
8 cin >> ch;
9
10 cout << "ASCII value of '" << ch << "' is: " << (int)ch << endl;
11
12 return 0;
13}

Output

Enter a character: A
ASCII value of 'A' is: 65

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 0
Digit character to number is ch - '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.