File reading problem
Hi! I have a program with a class that needs to be able to write
itself to a file in clear text format. The file has two integers and
vector of struct objects. The struct has a string that can consist of
one or more words and a few integers. I'm able to create the file
properly, as confimed by viewing it in a text editor, but something
goes wrong when I tried to read it. I've made a test program
illustrating the problem:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct s_t
{
s_t() {}
s_t(const string& si, int xi, int yi) : s(si), x(xi), y(yi) {}
string s;
int x, y;
friend ostream& operator<<(ostream& os, const s_t& rhs);
friend istream& operator>>(istream& is, s_t& rhs);
};
ostream&
operator<<(ostream& os, const s_t& rhs)
{
os << rhs.s << endl;
os << rhs.x << ' ' << rhs.y;
return os;
}
istream&
operator>>(istream& is, s_t& rhs)
{
getline(is, rhs.s);
is >> rhs.x >> rhs.y;
return is;
}
void
readit()
{
int x = 0, y = 0;
vector<s_t> vec;
ifstream in("foo.txt");
in >> x >> y;
{
s_t temp;
while (in >> temp) vec.push_back(temp);
}
in.close();
cout << x << ' ' << y << endl;
cout << vec.size() << endl;
for (unsigned int i = 0; i < vec.size(); i++)
cout << vec.at(i) << endl;
}
int
main()
{
int x = 4711, y = 1337;
vector<s_t> vec;
vec.push_back(s_t("foo bar", 33, 22));
vec.push_back(s_t("bar baz", 11, 99));
ofstream out("foo.txt");
out << x << ' ' << y << endl;
for (unsigned int i = 0; i < vec.size(); i++)
{
out << vec.at(i);
if (i < vec.size() - 1)
out << endl;
}
out.flush();
out.close();
readit();
}
When I run it, I get this output:
4711 1337
0
so it reads the first two numbers ok but reading the s_t objects
doesn't work because the vector is empty afterwards...
Any help appreciated.
- E