C++ 将cout写入文件,然后返回到终端

C++ 将cout写入文件,然后返回到终端,c++,file,cout,freopen,C++,File,Cout,Freopen,我目前正在编写一个程序,将cout写入一个文件,直到用户按下control D。之后,我想再次将cout写入终端。这是我的代码示例 freopen(outputfile,"w",stdout); for(;;) { if(cin.fail()) //user pressed control-D { break; } string s; cin >> s; cout << s << endl; } cout <&l

我目前正在编写一个程序,将cout写入一个文件,直到用户按下control D。之后,我想再次将cout写入终端。这是我的代码示例

freopen(outputfile,"w",stdout);

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

cout << "COMPLETE" << endl;
freopen(输出文件,“w”,标准输出);
对于(;;)
{
if(cin.fail())//用户按下了control-D
{
打破
}
字符串s;
cin>>s;

无法解决。我想要的是这个

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

for(;;)
{
    if(cin.fail())
    {
    break;
    }
string s;
cin >> s;
tempfile << s << endl;  
}
tempfile.close();
cout << "COMPLETE" << endl;
流tempfile的
;
tempfile.open(“temp.txt”);
对于(;;)
{
if(cin.fail())
{
打破
}
字符串s;
cin>>s;

tempfile
if(cin.fail())//用户按下control-D
除了声明的条件外,还有很多原因
cin.fail()
是正确的!!不要使用
freopen
,您会丢失标准输出流。请更改流缓冲区
cout
保留,然后将其交换回来。(这假定您只使用
cout
,而不使用
stdout
。)