Convert int array to a string in C++
This post will discuss how to convert an int array to a string in C++.
1. Using to_string() function
The idea is to iterate over the array using a for-loop and concatenate all values in an array to a std::string. This can be done using the std::to_string function, which returns the string representation of an integer. This can be implemented as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> std::string convert(int arr[], int n) { std::string s; for (int i = 0; i < n; i++) { s += std::to_string(arr[i]); } return s; } int main() { int arr[] = {0, 1, 1, 0, 1, 1, 0, 0}; int n = sizeof(arr) / sizeof(*arr); std::string s = convert(arr, n); std::cout << s << std::endl; // 01101100 return 0; } |
2. Using String Stream
Another option is to use the std::stringstream to concatenate integers to a string. The std::stringstream is a stream class to operate on strings. The basic idea remains the same as above, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <string> #include <sstream> std::string convert(int arr[], int n) { std::stringstream ss(""); for (int i = 0; i < n; i++) { ss << arr[i]; } return ss.str(); } int main() { int arr[] = {0, 1, 1, 0, 1, 1, 0, 0}; int n = sizeof(arr) / sizeof(*arr); std::string s = convert(arr, n); std::cout << s << std::endl; // 01101100 return 0; } |
That’s all about converting an int array to a string in C++.
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 :)