C++打印控制台输出到txt文件



我正试图将控制台的所有输出打印到一个txt文件中。我知道如何简单地这样做:

int main()
{
ofstream outfile;
outfile.open("Text.txt");
outfile << "Hello World!n";
outfile.close();
}

但我正试图在这个程序中做到这一点,因为我的大多数函数都使用"cout",所以每次打印都使用"myfile"是非常健壮的。我正在尝试用这种方式,但不确定是否将其作为一种功能来做更好:

int main()
{
string st;
ofstream myfile;
myfile.open("Game.txt");
myfile << st;
Player P1("player 1 ", true);
Player P2("Computer", false);
Board myboard(1);

int cardno;
int pos;
cout << "nnn               Please select a position on Board: ";
getch();
myfile.close();
cout << st;
return 1;

试试这个:

stream file; 
file.open("cout.txt", ios::out); 
string line; 
// Backup streambuffers of  cout 
streambuf* stream_buffer_cout = cout.rdbuf(); 
streambuf* stream_buffer_cin = cin.rdbuf(); 
// Get the streambuffer of the file 
streambuf* stream_buffer_file = file.rdbuf(); 
// Redirect cout to file 
cout.rdbuf(stream_buffer_file); 
cout << "This line written to file" << endl; 
// Redirect cout back to screen 
cout.rdbuf(stream_buffer_cout); 
cout << "This line is written to screen" << endl; 
file.close();

试试这个:

using namespace std;
ofstream output("myfile.txt");
int main()
{
cout << "Content to display on console";
output << "Content to display in file";
return 0;
}

我知道你想直接从控制台输出文件中的内容,那么这就可以了。控制台中显示的内容都将显示在文件中。这与g++编译器配合使用很好。

最新更新