C++ Program For int to char Conversion
Last Updated :
08 May, 2023
In this article, we will learn how to convert int to char in C++. For this conversion, there are 5 ways as follows:
- Using typecasting.
- Using static_cast.
- Using sprintf().
- Using to_string() and c_str().
- Using stringstream.
Let's start by discussing each of these methods in detail.
Examples:
Input: N = 65
Output: A
Input: N = 97
Output: a
1. Using Typecasting
Method 1:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: It is a technique for transforming one data type into another. We are typecasting integer N and saving its value in the data type char variable c.
- Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
C++
// C++ program to convert
// int to char using typecasting
#include <iostream>
using namespace std;
// Driver code
int main()
{
int N = 97;
cout << char(N);
return 0;
}
The time complexity is O(1) and an auxiliary space is O(1).
Method 2:
- Declaration and initialization: To begin, we will declare and initialize our integer with the value to be converted.
- Typecasting: Declare another variable as character c and assign the value of N to the C
- Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
C++
// C++ program to convert
// int to char using typecasting
#include <iostream>
using namespace std;
// Driver code
int main()
{
int N = 65;
char c = N;
cout << c;
return 0;
}
2. Using static_cast
The integer can be converted to a character using the static_cast function. Below is the C++ program to convert int to char using static_cast:
C++
// C++ program to convert
// int to char using static_cast
#include <iostream>
using namespace std;
// Driver code
int main()
{
int N = 65;
char c = static_cast<char>(N);
cout << c;
return 0;
}
3. Using sprintf()
Allot space for a single int variable that will be converted into a char buffer. It is worth noting that the following example defines the maximum length Max_Digits for integer data. Because the sprintf function sends a char string terminating with 0 bytes to the destination, we add sizeof(char) to get the char buffer length. As a result, we must ensure that enough space is set aside for this buffer.
Below is the C++ program to convert int to char using sprintf():
C++
// C++ program to convert
// int to char using sprintf()
#include <iostream>
using namespace std;
#define Max_Digits 10
// Driver code
int main()
{
int N = 1234;
char n_char[Max_Digits +
sizeof(char)];
std::sprintf(n_char,
"%d", N);
std::printf("n_char: %s \n",
n_char);
return 0;
}
4. Using to_string() and c_str()
The to string() function transforms a single integer variable or other data types into a string. The c_str() method converts a string to an array of characters, terminating with a null character.
Below is the C++ program to convert int to char using to_string() and c_str():
C++
// C++ program to convert
// int to char using sto_string()
// and c_str()
#include <iostream>
using namespace std;
// Driver code
int main()
{
int N = 1234;
string t = to_string(N);
char const *n_char = t.c_str();
printf("n_char: %s \n",
n_char);
return 0;
}
5. Using stringstream
A stringstream connects a string object to a stream, allowing you to read from it as if it were a stream (like cin). Stringstream requires the inclusion of the sstream header file. The stringstream class comes in handy when processing input.
Below is the C++ program to convert int to char using stringstream:
C++
// C++ program to convert
// int to char using
// stringstream
#include <iostream>
using namespace std;
#include <sstream>
// Driver code
int main()
{
int N = 1234;
std::stringstream t;
t << N;
char const *n_char =
t.str().c_str();
printf("n_char: %s \n",
n_char);;
return 0;
}
Method: Converting int value to char by adding 0
C++
// C++ program to convert
// int to char using typecasting by adding zero
#include <iostream>
using namespace std;
//Driver code
int main()
{
int number = 65;
char charvalue = (char(number)+0);
cout << charvalue;
return 0;
}
Time complexity: O(1).
Auxiliary space: O(1).
Approach: ASCII value offset approach
Steps:
- Take an integer input from the user.
- Check if the input value corresponds to a valid character in the ASCII table by checking the range of the input value.
- If the input value corresponds to a valid character, then add the corresponding offset value of '0' or 'A' (depending on the input) to the integer value to get the corresponding character value.
- Output the corresponding character.
C++
#include <iostream>
using namespace std;
int main() {
int num = 65;
cout << "Enter an integer: " << num << endl;
char ch;
if(num >= 65 && num <= 90) {
ch = num;
} else if(num >= 97 && num <= 122) {
ch = num;
} else {
cout << "Invalid input." << endl;
return 0;
}
cout << "The corresponding character is: " << ch << endl;
num = 97;
cout << "Enter an integer: " << num << endl;
if(num >= 65 && num <= 90) {
ch = num;
} else if(num >= 97 && num <= 122) {
ch = num;
} else {
cout << "Invalid input." << endl;
return 0;
}
cout << "The corresponding character is: " << ch << endl;
return 0;
}
OutputEnter an integer: 65
The corresponding character is: A
Enter an integer: 97
The corresponding character is: a
Time Complexity: O(1), as there are no loops involved.
Auxiliary Space: O(1), as we are only using a single character variable to store the result.
Approach Name: Arithmetic Conversion
Steps:
- Calculate the number of digits in the input int value.
- Iterate through the digits from right to left, extracting each digit and adding the ASCII value of '0' to convert it to a char.
- Store the resulting char array in the provided output buffer.
C++
#include <iostream>
#include <cstring>
using namespace std;
void int_to_char(int num, char *result) {
int temp = num;
int len = 0;
while (temp > 0) {
len++;
temp /= 10;
}
for (int i = len - 1; i >= 0; i--) {
result[i] = num % 10 + '0';
num /= 10;
}
result[len] = '\0';
}
int main() {
int num = 12345;
char result[100];
int_to_char(num, result);
cout << result << endl;
return 0;
}
Time complexity: O(log10 n), where n is the input int value.
Space complexity: O(log10 n), where n is the input int value, due to the need to store the output char array.
Similar Reads
C++ Program For char to int Conversion In C++, we cannot directly perform numeric operations on characters that represent numeric values. If we attempt to do so, the program will interpret the character's ASCII value instead of the numeric value it represents. We need to convert the character into an integer.Example:Input: '9'Output: 9Ex
2 min read
C++ Program For Binary To Octal Conversion The problem is to convert the given binary number (represented as a string) to its equivalent octal number. The input could be very large and may not fit even into an unsigned long long int. Examples: Input: 110001110Output: 616 Input: 1111001010010100001.010110110011011Output: 1712241.26633 Simple
5 min read
C++ Program For String to Long Conversion In this article, we will learn how to convert strings to long in C++. For this conversion, there are 3 ways as follows: Using stol()Using stoul()Using atol() Let's start by discussing each of these methods in detail. Example: Input: s1 = "20" s2 = "30" Output: s1 + s2 long: 50 1. Using stol() In C++
3 min read
C++ Program For String to Double Conversion There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++. Methods to Convert String to Double We can convert String to Double in C++ using the following methods: Using stod() Fun
3 min read
C++ Program For Hexadecimal To Decimal Conversion The hexadecimal numbers are base 16 numbers that use 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all digits. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). Decimal numbers are base 10 numbers with 10 symbols to represent all digits. In this article, we will l
3 min read
C++ Program For Decimal To Hexadecimal Conversion In this article, we will learn to write a C++ program to convert a decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. In the decimal system, we use ten digits (0 to 9) to represent a number, while in the hexadecimal system, we use sixte
3 min read
Convert String to Char Array in C++ In C++, we usually represent text data using the std::string object. But in some cases, we may need to convert a std::string to a character array, the traditional C-style strings. In this article, we will learn how to convert the string to char array in C++.ExamplesInput: str = "geeksforgeeks"Output
4 min read
How to Convert Char Array to Int in C++ In C++, a character array is treated as a sequence of characters also known as a string. Converting a character array into an integer is a common task that can be performed using various methods and in this article, we will learn how to convert char array to int in C++. Example Input:char arr1[] ="1
2 min read
How to Convert ASCII Value into char in C++? In C++, ASCII (American Standard Code for Information Interchange) values are numerical representations of characters that are used in the C++. In this article, we will learn how to convert an ASCII value to a char in C++. Example: Input: int asciiValue = 65; Output: Character for ASCII value 65 is:
2 min read
C Program to Extract Characters From a String Character extraction can be done by iterating through the string in the form of a character array. It basically means plucking out a certain amount of characters from an array or a string. Now, to take input in C we do it by using the following methods: scanf("%c",&str[i]); - Using a loopscanf("
2 min read