convert char to C
To convert a char
to an integer in C++, you can use the typecast operator. Here's an example:
char c = 'A';
int i = static_cast<int>(c);
In this example, we have a char
variable c
with the value 'A'
. To convert it to an integer, we use the static_cast<int>
operator to cast c
to an int
. The resulting value is stored in the int
variable i
.
The static_cast
operator is used for explicit type conversions in C++. It tells the compiler to interpret the value of c
as an int
and perform the conversion accordingly. The resulting int
value will have the ASCII value of the character 'A'
, which is 65.
By using the static_cast<int>
operator, we ensure that the type conversion is done explicitly and safely. This helps to make the code more readable and maintainable.
Note: It's important to be cautious when converting char
values to integers, especially if the char
represents a digit character. In C++, the ASCII values for digit characters are not guaranteed to be consecutive. To convert a digit character to its corresponding integer value, you can subtract the ASCII value of '0'
from the char
value. For example:
char digit = '5';
int value = digit - '0';
In this example, the difference between the ASCII value of '5'
and '0'
is 5, so the resulting int
value will be 5.