Writing cout to a file and then back to terminal

225 Views Asked by At

I'm currently writing a program that writes cout to a file, until the user presses control D. After that I would like to cout again to the terminal. Here is a sample of my code

freopen(outputfile,"w",stdout);

for(;;)
{
    if(cin.fail())    //user pressed control-D
    {
    break;
    }
string s;
cin >> s;
cout << s << endl;
}

cout << "COMPLETE" << endl;

The "COMPLETE" cout is still being written to my file. How can I stop this so any couts not in the loop are normal and printing back to the terminal

Thanks in advance

1

There are 1 best solutions below

0
On

Solved. What I wanted was this

ofstream tempfile;
tempfile.open ("temp.txt");

for(;;)
{
    if(cin.fail())
    {
    break;
    }
string s;
cin >> s;
tempfile << s << endl;  
}
tempfile.close();
cout << "COMPLETE" << endl;