Tanveer Alam
Tanveer Alam

Reputation: 71

Displaying a character as a decimal number with cout

In the C programming language, I can use printf to display a character and its decimal equivalent with code like this

char c='e';
printf( "decimal value: %d   char value: %c\n",c,c);

How can I do the same in C++ using cout? For example, the following code displays the character, but how would I get cout to print the decimal value?

char c='e';
cout << c;

Upvotes: 4

Views: 13481

Answers (3)

Mohit Jain
Mohit Jain

Reputation: 30489

cout << +c;

Unary + cast operator will implicitly convert char to int.

Demo here

From 5.3.1 Unary operators aka expr.unary.op

[7] The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand.


Further readings:

Upvotes: 14

Arun A S
Arun A S

Reputation: 7006

You can cast the character to an int to obtain the decimal value in C++, like

char c='e';
std::cout << "Decimal : " << (int)c << std::endl;
std::cout << "Char : " << c;

By doing (int)c , you can temporarily convert it to an int and get the decimal value.

This process is known as type casting.

Upvotes: 4

Potatoswatter
Potatoswatter

Reputation: 137770

The best C++ way to cast c to int is static_cast< int >( c ).

Upvotes: 8

Related Questions