我想只使用一个函数将输出写入 cmd 窗口或日志文件。我发现最好的是这棵树 here .
所以这段代码(对引用源的微小改动)对我有效到 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++ 代码。
最佳答案
请查看函数原型(prototype)的下一个链接: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);
关于c++ - 将 cout 引用到变量位置(文件或 cmd),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22477703/