Convert Integer to Char in C++
Convert Integer to Char in C++ (5 Programs).
1#include <iostream>2using namespace std;34int main() {5 int num = 65;67 // Method 1: Direct casting8 char ch1 = (char)num;910 // Method 2: Using static_cast11 char ch2 = static_cast<char>(num);1213 cout << "Integer: " << num << endl;14 cout << "Character (method 1): " << ch1 << endl;15 cout << "Character (method 2): " << ch2 << endl;1617 return 0;18}
Output
Integer: 65 Character (method 1): A Character (method 2): A
What's going on
The program converts an integer (like 65) into its corresponding character (like 'A') based on the ASCII value. In the ASCII system, each character has a unique number:
This conversion is essential when you need to display characters based on numeric values or work with character encoding.
Header File Used
This header provides:
1#include <iostream>
Declaring Variables
The program declares:
int num = 65;
Method 1: Direct Casting (C-style)
char ch1 = (char)num;
This method uses C-style casting:
This is the simplest and most direct method, but it's considered less safe in modern C++ because it doesn't perform type checking.
Example:
Method 2: Using static_cast (C++ style)
char ch2 = static_cast<char>(num);
This method uses C++ style casting:
static_cast<char>(65) converts the integer 65 to the character 'A'.
This method is preferred over C-style casting because:
Other Methods (Mentioned but not shown in code)
The program description mentions three additional methods:
Method 3: Using ASCII values directly
char ch3 = 65; // Direct assignment
This works because characters are stored as integers internally.
Method 4: Using char arithmetic
char ch4 = 'A' + (num - 65);
This calculates the character by adding an offset to a base character.
Method 5: Using sprintf
char buffer[2];
sprintf(buffer, "%c", num);
char ch5 = buffer[0];
This uses the C function sprintf to format the integer as a character.
Understanding ASCII Values
ASCII (American Standard Code for Information Interchange) is a character encoding standard:
When you convert an integer to a character, C++ interprets that integer as an ASCII code and returns the corresponding character.
Displaying Results
The program prints:
Output:
Integer: 65
Character (method 1): A
Character (method 2): A
Both methods produce the same result because they both convert 65 to 'A'.
1cout << "Integer: " << num << endl;2cout << "Character (method 1): " << ch1 << endl;3cout << "Character (method 2): " << ch2 << endl;
Important Considerations
Valid ASCII Range
: Standard ASCII values range from 0 to 127. Extended ASCII goes up to 255. Values outside this range may produce unexpected results.
Type Safety
: static_cast is safer than C-style casting because:
Character vs Integer
: Remember that:
return 0;
This ends the program successfully.