How to write a variable Std::vector<Std::tuple<>> into a txt file?

Asked

Viewed 32 times

1

I have the tuple vector written in C++, defined as:

std::vector<std::tuple< float, float>> ASK_Mod;

I populated it, and tried to save it in a new file . txt as defined in the function, however, it only works for Vectors without tuples.

std::ofstream outfile("ASKModulation.txt");
outfile.open("ASKModulation.txt");


if(outfile.is_open())
{

    std::copy(ASK_ModulatedWave.rbegin(), ASK_ModulatedWave.rend(), std::ostream_iterator<float>(outfile, "\n"));

}else
{
    std::cout << "ERROR! Could not export!" << std::endl;
}
outfile.close();

The error that returns is:

/usr/include/c++/7/bits/stl_algobase. h:324:18: error: no match for ḍ Operator=' (operand types are ːStd::ostream_iterator' and ḍ Std::tuple') *__result = *__first;

How can I save the Ask_mod variable to a file. txt?

1 answer

2


One of the things that needs to be done is to define the << operator for the type you want to play in the stream. In your case, the << operator for Std::tuple needs to be defined.

std::ostream& operator<<( std::ostream& os, const std::tuple< float, float>& tp)
{
    const auto [p1, p2] = tp;
    os << p1;
    os << p2;
    return os;
}

I couldn’t make it work with Std::copy, but a loop solves your problem.

std::for_each(ASK_Mod.rbegin(), ASK_Mod.rend(), [&](const std::tuple<float, float>& tp) {
    outfile << tp;
});

Link to compiling solution: https://godbolt.org/z/4ECSRK

  • 1

    So, I liked what you did, but the generated file is empty, and I checked if it enters the loop you created, and enters, but does not record apparently

  • 1

    @Fourzerofive The file was opened twice, in the constructor and in the open() method. This meant that the contents were not written. I updated the link to a working solution :)

  • So grateful, so perfect!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.