Home > database >  How to write vectors member to file
How to write vectors member to file

Time:01-25

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];
}

CodePudding user response:

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;
}

CodePudding user response:

Example:

#include <fstream>
#include <vector>

int main() {
    std::vector<int> myVector = {1, 2, 3, 4, 5};

    std::ofstream outFile("vector.txt");
    for (int num : myVector) {
        outFile << num << " ";
    }
    outFile.close();
    return 0;
}
  • Related