Eric Lilja wrote:
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;
After this, the next character in the input stream should be a '\n'.
{
s_t temp;
This will now read to the first newline in the stream and put the result
into temp.s. Since the first character is a newline, temp.s will be empty.
Then in will try to put the contents of what's stored as a string into
temp.x. In this case, in finds 'f', and fails. Thus the reading of the two
ints will become a noop, and the test fails.
I suggest you look up the ignore() member function of istream. You need to
ignore the rest of the line.
before the getline() call. Now that program works just fine. However,
in the file. Hmm.