Convert an int array to a string in C++

In this article, we will discuss some approaches to converting an integer array into a string in C++ along with some examples. Below are the multiple methods to do so:

  • Using to_string function
  • Using push_back() method
  • Using string stream

to_string() method to convert int array to string :

Generally, the to_string method takes a single value of any data type as a parameter and converts it into a string data type. Here, initially, we consider an empty string and we pass every integer value in the array as a parameter to this function and convert it into a string, in parallel we will be appending it to the string we considered earlier.

Example Code : 

#include <iostream>
using namespace std;
int main() {
    int arr[] = {1, 2, 3};
    string s = "";
    for(int x : arr)
    {
        s += to_string(x);
    }
    cout<<"string : "<< s<<"\n";
    return 0;
}

Output : 

string : 123

push_back() method to convert int array to string :

Using this method we will push each element of the array to the string. During this process, we will add the zero(‘0’) to the array element so that the integer will be pushed as a string.

Example code :

#include <iostream>
using namespace std;
int main() {
    int arr[] = {1, 2, 3};
    string s;
    for(int x : arr)
    {
        s.push_back(x + '0');
    }
    cout<<"string : "<< s<<"\n";
    return 0;
}

Output :

string : 123

Using string stream in C++ :

C++ provides us with a class called string stream class. We will perform read, write, and some other operations on string stream objects.

str() method in this class is used to get and set the content of the string object in the stream.

<<” used to add a new string to an object(write)

>>” used to read the content from the object(read)

Initially, we will create a string stream object. In order to do this we have to include a library called <sstream> and add every integer in the array to the string stream object.

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3};
    string s;
    stringstream o;
    for(int x : arr)
    {
        o << x;
    }
    s = o.str();
    cout<<"string : "<< s<<"\n";
    return 0;
}

Output :

string : 123

The above discussed are the simple approaches to convert an int array to a string. Hope you have understood the entire discussion.

Leave a Reply

Your email address will not be published. Required fields are marked *