[c++] Converting a char to ASCII?

I have tried lots of solutions to convert a char to Ascii. And all of them have got a problem.

One solution was:

char A;
int ValeurASCII = static_cast<int>(A);

But VS mentions that static_cast is an invalid type conversion!!!

PS: my A is always one of the special chars (and not numbers)

This question is related to c++ visual-studio-2010

The answer is


You can use chars as is as single byte integers.


A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

Uhm, what's wrong with this:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}