Summary: In this programming tutorial, we will learn different ways to convert a number of type int into a char pointer or array in C++.
Method 1: Using to_string() and c_str()
In this method, we first convert the given number into a c++-string and then transform it into the char*
type using the c_str() method.
#include <iostream>
using namespace std;
int main() {
int number = 123456;
//convert number to c++-string
string s = to_string(number);
//transform the string to char* using c_str()
const char* nchar = s.c_str();
cout << nchar;
return 0;
}
The c_str()
method returns a const char*
pointer to an array that has the same values as the string object with an additional terminating null-character (‘\0
‘).
Method 2: Using to_chars()
The to_chars() method defined in the <charconv>
header file converts an integer or a floating-point number into a sequence of char
.
#include <iostream>
#include <charconv>
using namespace std;
int main() {
int number = 123456;
//find the length of the number
int length = to_string(number).length();
//declare a char* pointer array of the same length
char* nchar = new char[length];
//convert int to char using the to_chars() method
to_chars(nchar, nchar+length, number);
cout << nchar;
return 0;
}
The three parameters which we have passed to the to_chars(first, last, value)
are :
first
– pointer to the beginning of the char*.last
– pointer to the last of the char*.value
– The integer to convert.
Method 3: Using Sprintf()
Unlike other methods, this method converts an integer to a char array.
In this method, we use the sprintf() method to format and write the given integer into the char
array.
#include <iostream>
using namespace std;
int main() {
int number = 1234567890;
//find the length of the number
int length = to_string(number).length();
//declare a char array of size = length+1
char nchar[length+1];
//convert int to char using the sprintf() method
sprintf(nchar, "%d", number);
cout << nchar;
return 0;
}
The three parameters which we have used in the sprintf(cstr, format, value)
are:
cstr
– pointer to the char array where the resulting c-string will be stored.format
– format specifier of thevalue
.value
– the integer to convert.
Related Topic: What is the difference between char* and char[] in C/C++?
These were the three ways using which we can convert an int to char array in C/C++ programming languages.