c++ - 将 cout 引用到变量位置(文件或 cmd)

标签 c++ output

我想只使用一个函数将输出写入 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/

相关文章:

python - 如何使用一个打印语句但仍打印多行

php - 强制下载脚本和读取文件 : Why readfile outputs my html page?

c++ - sscanf c++ 将字符串拆分为整数有时不起作用

c++ - 4 字节对齐的指针是否使用任何填充?

c++ - 如何判断函数参数是否可以安全删除

css - scss 输出单独的文件

c++ - 对多个客户数据使用 vector 和数组时,计算不正确

c++ - 为什么我们不能用右值 volatile int&& 初始化对 const int 的引用?

c - 如何使我的输出仅显示我的 c 支票生成器程序所需的内容

java - 如何以表单形式显示 Netbeans 的输出?