Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a character as a decimal number with cout

Tags:

c++

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;
like image 235
Tanveer Alam Avatar asked Nov 28 '22 20:11

Tanveer Alam


1 Answers

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:

  • cppreference > Utilities Library > Type support > std::is_integral to understand the meaning of integral types.
  • cppreference > C++ > C++ Language > Expressions > Implicit conversions > Numeric promotions > Integral promotion
like image 110
Mohit Jain Avatar answered Dec 05 '22 10:12

Mohit Jain