How to use sprintf() In C++
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; } |
Output
n_char: 1234
C++ Program For int to char Conversion
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: AInput: N = 97
Output: a
Contact Us