将cout引用到一个变量位置(文件或cmd)



我想只使用一个函数将输出写入cmd窗口或日志文件。我找到的最好的方法就是这棵树。

所以这段代码(从参考源的微小变化)为我工作到90%:

void outputTest(){
cout << "Testing a new version of output." << endl;
std::ofstream realOutFile;
bool outFileRequested = true;
if(outFileRequested)
    realOutFile.open("foo.txt", std::ios::out);
std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);
outFile << "test" << endl;
keep_window_open();
}

现在,我想把文件写入另一个位置,而不是"foo.txt"。所以我添加了以下内容:

string LogFile = config_.outputFiles+config_.projectName; //+"/RoomData.log"
ofstream realOutFile;
if (logFileRequested && config_.saveLogs){
    realOutFile.open(LogFile+"/foo.txt", ios::out);
}
std::ostream & outFile = (logFileRequested ? realOutFile : cout);

我也试着只传递一个字符串,但在这两种情况下,我得到的函数调用不匹配。

有办法解决这个问题吗?为什么传递字符串不同于传递"字符串内容"?

谢谢你的帮助。

注:对不起,我没有正确格式化c++代码。

请参阅下一个功能原型链接:http://www.cplusplus.com/reference/fstream/ofstream/open/

open函数接收const char*作为第一个参数。这样就可以了->

string LogFile = config_.outputFiles+config_.projectName; //+"/RoomData.log"
ofstream realOutFile;
if (logFileRequested && config_.saveLogs){
    LogFile += "/foo.txt";
    realOutFile.open(LogFile.c_str(), ios::out);
}
std::ostream & outFile = (logFileRequested ? realOutFile : cout);

最新更新