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:

  1. Using typecasting.
  2. Using static_cast.
  3. Using sprintf().
  4. Using to_string() and c_str().
  5. Using stringstream.

Let’s start by discussing each of these methods in detail.

Examples:

Input: N = 65 
Output:

Input: N = 97 
Output: a

Similar Reads

1. Using Typecasting

Method 1:...

2. Using static_cast

...

3. Using sprintf()

...

4. Using to_string() and c_str()

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:...

5. Using stringstream

...

Contact Us