mines not so well, I can't figure out why this isn't working. I'm learning how to write and read from a file,
This program take 3 words (I know I wrote string's name as Sentence, but its just supposed to work for words) and stores them* into text file. It does that part correctly, but then it can't read it out correctly! What am I doing wrong?
working for me with stringstream, which is almost exactly like fstream, but easier to demo online. Did you try to enter more than three space-separated words?
You can use seekg. I opened the file with truncate below so it starts empty even if it already has something in it. Alternatively you could open it with ios_base::app instead of trunc to append lines to the existing contents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main() {
fstream f("words.txt", ios_base::in|ios_base::out|ios_base::trunc);
string word;
for (int i = 0; i < 3; i++) {
cin >> word;
f << word << '\n';
}
f.seekg(0);
while (f >> word)
cout << word << '\n';
return 0;
}