C++: Character Codes

Bjarne-stroustrup
 

Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).

For example, the character ‘a’ (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).

Conversely, given a code, print out the corresponding character.

char is already an integer type in C++, and it gets automatically promoted to int. So you can use a character where you would otherwise use an integer. Conversely, you can use an integer where you would normally use a character, except you may need to cast it, as char is smaller.

In this case, the output operator << is overloaded to handle integer (outputs the decimal representation) and character (outputs just the character) types differently, so we need to cast it in both cases.

#include <iostream>

int main() {
	std::cout << (int)'a' << std::endl; // prints "97"
	std::cout << (char)97 << std::endl; // prints "a"
	return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.

Subscribe to TFE Times

Enter your email address to become a member of TFE Times today!