the ifstream part(reading .csv file into array) works perfectly but the ofstream part(printing array into .txt file) gives error. got error no match for 'operator<<'
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
ifstream in("test.csv");
string line, field;
vector <vector <string>> array;
vector <string> v;
while (getline(in, line))
{
v.clear();
stringstream ss(line);
while(getline(ss,field,','))
{
v.push_back(field);
}
array.push_back(v);
}
ofstream myfile("test1.txt");
myfile<<array;
myfile.close();
error message:
error: no match for 'operator<<' (operand types are 'std::ofstream' {aka 'std::basic_ofstream<char>'} and 'std::vector<std::vector<std::__cxx11::basic_string<char> > >')
CodePudding user response:
There is no operator overloaded for the std::vector<std::vector<std::string>>
in the std::ofstream
, so you can't do that. One way you could do this is:
std::ofstream myfile("test1.txt");
if (myfile)
{
//https://www.cplusplus.com/reference/ostream/ostream/write/
for (auto& elem : array)
{
for (auto& str : elem)
{
myfile.write(str.data(), str.size());
}
}
myfile.close();
}
I would prefer JSON, for serializing this type of stuff.