How to use to_string() and c_str() In C++

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;
}


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