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;
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With