vector to string c++
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::ostringstream oss;
for (const auto& num : numbers) {
oss << num << " ";
}
std::string result = oss.str();
std::cout << "Resulting string: " << result << std::endl;
return 0;
}
Include Libraries: Import necessary libraries (
iostream
,vector
,string
,sstream
) to work with vectors and strings.Main Function: Define the
main()
function, the entry point of the program.Vector Initialization: Create a vector named
numbers
and initialize it with integers 1 to 5.String Stream Object: Declare an
ostringstream
object namedoss
. This object will be used to manipulate the content of the string.Loop Through Vector: Iterate through each element in the
numbers
vector using a range-basedfor
loop.Append Numbers to String Stream: Inside the loop, each number from the vector is appended to the
ostringstream
object followed by a space.Convert String Stream to String: Get the resulting string from the
ostringstream
object by callingoss.str()
and store it in theresult
variable.Display Result: Output the final string (
result
) containing the vector elements separated by spaces to the standard output usingstd::cout
.Return: End the
main()
function and return 0 to indicate successful completion of the program.