In C++, you can convert a character to its ASCII code (or ASCII value) by simply assigning the character to an integer variable.
Here's an example:
char myChar = 'A';
int asciiValue = myChar; // Conversion: Assigning the character to an integer variable
cout << "ASCII value of " << myChar << " is: " << asciiValue << endl;
In the above example, we have a character variable myChar initialized with the value 'A'. By assigning myChar to an integer variable asciiValue, the character is implicitly converted to its ASCII code. We can then print the ASCII value using cout.
Note that in C++, characters are internally represented as their corresponding ASCII values. When you assign a character to an integer variable, the ASCII value is stored in that variable.
If you want to explicitly convert a character to its ASCII code, you can use the static_cast operator. Here's an alternative way to perform the conversion:
char myChar = 'A';
int asciiValue = static_cast<int>(myChar); // Explicit conversion using static_cast
cout << "ASCII value of " << myChar << " is: " << asciiValue << endl;
Both approaches will yield the same result, converting the character to its ASCII code.