-1

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

Rob V
  • 17
  • 2
  • 4
  • 3
    `if(cin.fail()) //user pressed control-D` There's plenty of reasons `cin.fail()` is true aside the stated condition!! – πάντα ῥεῖ Nov 21 '14 at 02:11
  • Don't use `freopen`, you loose the standard-output-stream. Change the stream-buffer `cout` holds instead, and swap it back after. (This pre-supposes you only use `cout` and not `stdout` though.) – Deduplicator Nov 21 '14 at 02:14

1 Answers1

0

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;
Rob V
  • 17
  • 2
  • 4