An integer can be converted to a character when its value represents a valid character code or a decimal digit.
- Character-code conversion can map values such as 65 to 'A' and 97 to 'a'.
- A decimal digit can be converted to its character form using the '0' character offset.
Examples:
Input: N = 65
Output: AInput: N = 97
Output: a
Approaches to Convert int to char in C++
The following approaches can be used to convert an integer to a character in C++:
1. Using C-style Type Casting
C-style type casting can explicitly convert an integer value to a character.
#include <iostream>
using namespace std;
int main()
{
int num = 65;
// Convert integer to character
char ch = (char)num;
cout << ch;
return 0;
}
Output
A
Explanation
- The integer 65 is explicitly converted to char.
- In ASCII, 65 represents the character 'A'.
2. Using static_cast<char>()
static_cast<char>() is the preferred C++ approach for explicitly converting an integer to a character.
#include <iostream>
using namespace std;
int main()
{
int num = 97;
// Explicitly convert integer to character
char ch = static_cast<char>(num);
cout << ch;
return 0;
}
Output
a
Explanation
- static_cast<char>() explicitly converts 97 to char.
- In ASCII, 97 represents the character 'a'.
3. Using Implicit Conversion
C++ can automatically convert an integer to a character when an int value is assigned to a char variable.
#include <iostream>
using namespace std;
int main()
{
int num = 65;
// Implicit conversion from int to char
char ch = num;
cout << ch;
return 0;
}
Output
A
Explanation
- The integer 65 is automatically converted to char during assignment.
- The resulting character is 'A'.
4. Using Direct Initialization
A char variable can also be initialized directly using an integer value.
#include <iostream>
using namespace std;
int main()
{
int num = 97;
// Directly initialize char from integer
char ch(num);
cout << ch;
return 0;
}
Output
a
Explanation
- The char variable is initialized directly with the integer value 97.
- The value is converted to the corresponding character.
5. Converting a Digit to Its Character Form
When the integer represents a single decimal digit from 0 to 9, adding '0' converts it to the corresponding character.
#include <iostream>
using namespace std;
int main()
{
int digit = 5;
// Convert digit to its character representation
char ch = digit + '0';
cout << ch;
return 0;
}
Output
5
Explanation
- The integer 5 represents the numeric digit 5.
- Adding '0' maps it to the character '5'.
- This method is valid for digits from 0 to 9.