ofstream t;
t.open(mainTape.c_str());
t << 1.0 << ',' << 3.1 << ',' << 1.0 << '|';
t << 1.0 << ',' << 3.2 << ',' << 1.0 << '|';
t << 1.0 << ',' << 3.3 << ',' << 1.0 << '|';
t << 1.0 << ',' << 3.4 << ',' << 1.0 << '|';
t << 1.0 << ',' << 3.5 << ',' << 1.0 << '|';
t.flush();
t.close();
ifstream i;
i.open(mainTape.c_str());
float a,b,c;
char g;
i.seekg((3*sizeof(float) + 3*sizeof(char))); // THERE
i >> a >> g >> b >> g >> c >> g;
cout << a << ' ' << b << ' ' << c << ' ' << endl;
i.seekg(-1*(3*sizeof(float) + 3*sizeof(char)));
i >> a >> g >> b >> g >> c >> g;
cout << a << ' ' << b << ' ' << c << ' ' << endl;
i.close();
WHat I'm trying to do is rather simple: Write a few values to a file, separated by commas and '|'. Read the second set of values from the file, print it to the screen, go back in a file, read the same values again, and print them to the screen again.
And then there's that place in the code, bookmarked by a 'THERE' comment.
The code works OK if i remove that line. All the values are printed OK. But once that line's there, all I see is zero'es. It doesn't read from file properly. Why's that? How can I fix it?
I'd really, really be grateful if someone could help me with that one!
You're trying to see across text data as if it were binary data. You can't do that.
Typically speaking, seekg only works with binary data. it can also work with text data provided you know the number of characters that exist in the strings you want to seek over -- but usually you don't.
sizeof(float) and seekg() both work on the size in bytes. They don't work on the textual representation in characters. For example, sizeof(float) is 4 bytes on most machines, but the text in your file is only 3 characters.
Ok, thanks for the tip, however, it's still problematic. If i open these two files using ios_base::binary, I can't really use streams there. At least, I think, because after adding the necessary flags, the code still doesn't work. Any tips on how to fix that?