0
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void writeFile(fstream& file)
{
    file.open("writing.txt", ios::out);
    if (file.is_open())
    {
        string holdLine;
        cout << "Please write to the file from console!!!" << endl;
        while (getline(cin, holdLine, '-'))
            file << holdLine<< endl;
    }
    file.close();
}

void readFile(fstream& file)
{
    file.open("writing.txt", ios::in);
    if (file.is_open())
    {
        string holdLine;
        while (getline(file, holdLine))
        {
            cout << holdLine << endl;
        }
    }
    file.close();
}


int main()
{
    fstream sampleFile;
    writeFile(sampleFile);
    readFile(sampleFile);

}

// I am guessing this while (getline(cin, holdLine, '-')) loop is the one causing problem // I test readFile() and it works fine but whenever writeFile() runs it goes on infinite loop

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Try taking a look at [this answer](https://stackoverflow.com/a/35202275/12162258) for a better way of writing a file to `stdout`. – thisisrandy Jul 11 '22 at 03:50
  • If you want the input to be terminated by `-`, then what is the loop for? Why don't you simply call `getline` once? – user17732522 Jul 11 '22 at 03:59
  • @user17732522 Thanks a lot your idea fixed it. I forget the fact that getline() will always take lines till the delim char meaning it can take thousand of lines. :) – user19523629 Jul 11 '22 at 06:18

0 Answers0