4

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; 
1
  • 1
    Why C language tag? Commented Apr 18, 2015 at 4:06

3 Answers 3

14
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:

Sign up to request clarification or add additional context in comments.

2 Comments

Love this answer, because this let's me use the same function body for all template arguments char, short, int, long, long long!
@mxmlnkn Thanks. I am glad that you liked it.
8

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

Comments

4

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.

1 Comment

A C style cast, really?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.