Below is a code I just tried, which writes to a text file and then attempts to read it back. The output file shows up correctly, but the input stream seems to not be working the way I want. What am I doing wrong with the input stream here?
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace std;
int main() {
//Fill a simple 2D vector
vector<vector<int> > vv;
vector<int> v1, v2;
for (int i=0; i<10; i++) {
v1.push_back(i);
v2.push_back(2*i);
}
vv.push_back(v1);
vv.push_back(v2);
//Open an output stream and write values to it
ofstream out("out.txt");
if (!out) {
cout << "Failed to create output stream." << endl;
cin.get();
return 0;
}
out << vv.size(); //size of 2d vector
for (int i=0; i<vv.size(); i++) {
out << vv[i].size(); //size of this current 1d vector
for (int j=0; j<vv[i].size(); j++) {
out << vv[i][j]; //each integer one-by-one
}
}
out.close();
//Now try to read same file back
ifstream in("out.txt");
if (!in) {
cout << "Failed to create input stream." << endl;
cin.get();
return 0;
}
size_t size2d;
in >> size2d; //Should be size of 2d vector
cout << "2d vector size: " << size2d << endl;
cin.get();//pause to look
for (int i=0; i<size2d; i++) {
size_t size1d;
in >> size1d; //Should be size of next 1d vector
cout << "next 1d vector size: " << size1d << endl;
cin.get();//pause to look
for (int j=0; j<size1d; j++) {
int x;
in >> x; //Get and read back individual values
cout << x << " ";
cin.get();
}
cout << endl;
}
in.close();
cin.get();
return 0;
}
When I look at the output in a text editor (copied below), I see exactly what I expect - a 2, followed by a 10, followed by 0-9, then another 10, then 0-18. Then the ifstream fails me and says the 2d vector size is zero, and obviously does no further reading as a result.