How to convert a matrix of numbers to a string in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

std::string matrixToString(const std::vector<std::vector<int>>& matrix) {
    std::ostringstream oss;

    for (const auto& row : matrix) {
        for (const auto& element : row) {
            oss << element << " "; // Add each element followed by a space
        }
        oss << "\n"; // Add a newline after each row
    }

    return oss.str(); // Convert the stream to a string
}

int main() {
    std::vector<std::vector<int>> matrix = {
        {4, 7, 9, 18, 29, 0},
        {1, 9, 18, 99, 4, 3},
        {9, 17, 89, 2, 7, 5},
        {19, 49, 6, 1, 9, 8},
        {29, 4, 7, 9, 18, 6}
    };

    std::string result = matrixToString(matrix);
    
    std::cout << "Matrix as a string:\n" << result;
}

 
 
/*
run:
 
Matrix as a string:
4 7 9 18 29 0 
1 9 18 99 4 3 
9 17 89 2 7 5 
19 49 6 1 9 8 
29 4 7 9 18 6 
 
*/

 



answered May 24, 2025 by avibootz
...