How to write vectors member to file

72 Views Asked by At

I'm trying to write vector's members to file but I get this error for loop operation:

no operator "<<" matches these operands

How can I write those members to file?

std::ofstream raport;
raport.open("test.txt", std::ios_base::app);
    
std::vector<std::vector<float>> targetInputs = {
    {0.0f, 0.0f},
    {1.0f, 1.0f},
    {1.0f, 0.0f},
    {0.0f, 1.0f}
};

for (int i = 0;i < targetInputs.size(); i++) {
    
    raport << targetInputs[i];
}
1

There are 1 best solutions below

0
Pepijn Kramer On BEST ANSWER

Example with range based for loop. The const references are there since output should never modify the input data. The ostringstream is a standin stream for your file.

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::ostringstream raport;
    //raport.open("test.txt", std::ios_base::app);

    std::vector<std::vector<float>> targetInputs = {
        {0.0f, 0.0f},
        {1.0f, 1.0f},
        {1.0f, 0.0f},
        {0.0f, 1.0f}
    };

    for (const auto& values : targetInputs)
    {
        for (const auto& value : values)
        {
            raport << value << " ";
        }
        raport << "\n";
    }

    std::cout << raport.str();

    return 0;
}