Convert an int array to string in C++
This post will discuss how to convert an int array to a std::string in C++.
1. Using string stream
We can use a string stream to easily convert an int[] to a std::string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <sstream> int main() { int arr[] = { 1, 2, 3, 4 }; std::ostringstream os; for (int i: arr) { os << i; } std::string str(os.str()); std::cout << str; return 0; } |
Output:
1234
2. Using string::push_back function
Here, the idea is to push each element of the integer array to the end of the std::string using the string::push_back function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> int main() { int arr[] = { 1, 2, 3, 4 }; std::string str; for (int i: arr) { str.push_back(i + '0'); } std::cout << str; return 0; } |
Output:
1234
3. Using std::to_string function
We can also convert every int value to a string using std::to_string and construct a string out of all values.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> int main() { int arr[] = { 1, 2, 3, 4 }; std::string str; for (int i: arr) { str += std::to_string(i); } std::cout << str; return 0; } |
Output:
1234
4. Using std::transform function
Finally, we can use the STL algorithm std::transform, which applies the given function to the elements of the specified range and stores the result in another range, which begins at the specified output iterator. The given function can be a unary operation function or a lambda expression, or an object of a class implementing the () operator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <iterator> #include <algorithm> int main() { int arr[] = { 1, 2, 3, 4 }; std::string str; std::transform(std::begin(arr), std::end(arr), std::back_inserter(str), [](int const &i) { return i + '0'; }); std::cout << str; return 0; } |
Output:
1234
That’s all about converting an int array to string in C++.
Exercise: Extend the solution to join the values using a delimiter.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)