0

I have the following C++ code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main()
{
     fstream file;

     file.open("file.txt", fstream::in | fstream::out | fstream::app);

     file << "Ivan" << "\n" << "Ivan";

     string text = "";

     while (!file.eof()) {
         text = "";
         file >> text;
         cout << text;
     }

     file.close();
}

When I'm using cout to print that text to console, this gives me lots of white lines. And when I enter the .txt file, there are lots of "H" letters except for my text. I think the problem is in the loop.

White lines

"H" letters

Does somebody know what the problem is?

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Yutat
  • 1
  • `while (!file.eof()) {` should be avoided and may cause a bug: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Dec 10 '20 at 17:20
  • You are writing to a file then read after the position you have written. – drescherjm Dec 10 '20 at 17:22
  • what is the content of the file? – Raindrop7 Dec 10 '20 at 17:37
  • There are two photos above the last sentense of the question "H letters" and "White lines" – Yutat Dec 10 '20 at 17:41

1 Answers1

1

Remove the std::ios::app flag. Passing this flag seeks to the end of the stream, so in your case you are already at the "EOF" of the file, that is why your loop fails.

Here is info from cppreference.com:

app
seek to the end of stream before each write

Try this:

fstream file("data.txt", std::ios::in | std::ios::out);
if(!file)
    cout << "!file\n";

file << "Ivan" << "\n" << "Ivan";

string text = "";

while (file >> text)
    cout << text << ' ';

You can move back the read pointer to the beginning of the file after writing:

file << "Ivan" << "\n" << "Ivan";

file.seekg(0, std::ios::beg);

string text = "";

while (file >> text)
    cout << text << ' ';
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Maestro
  • 2,310
  • 7
  • 19