Output of char

May 27, 2019 at 1:53pm
Why does std::cout automatically convert the char variable I defined into the corresponding int from ASCII table? For example, in the code below, variable test is a char, but it prints out the integer 3.

1
2
3
  int main(){
  char test = 51;
  cout << test;}


Also, why does the following code give a value of 1? I know that single quote is used for single char, but it seems like it always outputs the last digit of the number in a single quote char. Thanks for helping.

1
2
3
  int main(){
  char test = '51';
  cout << test;}

May 27, 2019 at 2:09pm
#include<iostream>
using namespace std;
int main(){
char test= '5'; //char has 1bit only
cout << test;}
May 27, 2019 at 2:27pm
In your first example it is printing the character '3' not an integer. Decimal 51 is hexadecimal 33. Most ASCII tables are charted as hexadecimal.

'51' is interpreted as integer 13617. Trying to stuff that number into a char truncates the number, resulting in 1.

The most reliable way to have std::cout "see" your char variable as a number:

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
   char test = 51;

   std::cout << +test << '\n';
}
51

That will properly output the decimal number contained in a char variable, even if negative.
May 27, 2019 at 2:29pm
The corresponding ascii char of the integer 51 is the character '3'.
Last edited on May 27, 2019 at 2:29pm
May 27, 2019 at 2:35pm
I'm a newbie and don't know much but wouldn't the following code be better to output the integer value of a char?

 
cout << int{test} << '\n';
May 27, 2019 at 2:58pm
> '51' is interpreted as integer 13617.

A multicharacter literal, or ..., is conditionally-supported, has type int, and has an implementation-defined value.
http://eel.is/c++draft/lex.ccon#2



> wouldn't the following code be better to output the integer value of a char? cout << int{test} << '\n';

It (explicit conversion to int) is certainly clearer.


May 27, 2019 at 3:00pm
int(test) creates a temporary int, +test promotes a char variable, to be interpreted as an int.

For all practical purposes doing either really doesn't matter too much. A char is a simple Plain Old Data type, so creating one, even if a temporary, is not a terribly expensive operation.

I simply prefer to not create temporaries if it can be avoided. +temp is a round-about alternative to (int) temp or static_cast<int> (temp).

All three tell the compiler you want a char to be treated as an int for the operation.
Topic archived. No new replies allowed.