Convert int to char in C++

Hello C++ world,

New to this forum (and C++) and glad to join the community..
I have the following piece of code written in C:

 
  printf("The ASCII char of %d is %c\n", sum, sum);


When the sum is 89 the output will be:
 
The ASCII char of 89 is Y


It converts the decimal to the ASCII value (second 'sum').
Can this be done in C++ using the same variable..?

Thanks
Ray

Using: Ubuntu - Nano editor
I think you're trying to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
	char myChar = 89;

	std::cout << "The ASCII char of " << static_cast<int>(myChar) << " is " << myChar;
        
        //you can use (int)myChar; which is the C way of casting and is also accepted in C++, but the one used here is the standard

       //or this:
        std::cout << "\n";
        char myChar2 = 'Y';

	std::cout << "The ASCII char of " << static_cast<int>(myChar2) << " is " << myChar2;

	std::cin.ignore();
	std::cin.get();
	return 0;
}
Last edited on
Hello sasauke,

Thanks.

The code is now:
1
2
cout << "The ASCII char of " << sum << " is " 
       << static_cast<char>(sum) << "\n";


Greetings



That wouldn't really work.

with char sum = 'Y' it outputs "The ASCII char of Y is Y"

and with char sum = 89; it also outputs "The ASCII char of Y is Y"

That is because you are casting to char. You should cast to int static_cast<int>(sum), in order to get "The ASCII char of 89 is Y"
Last edited on
Hello

It works fine. It's part of a program that sums 8 bits together .

When I enter 00111101 I get decimal 61('sum') and ASCII char '='..

So.. thanks again.

Greetings

Last edited on
Topic archived. No new replies allowed.