2015-12-12 127 views
1

我做了一个非常大的程序,它一直向屏幕输出非常多的信息。 问题是,我无法一直在那里阅读并最终发现错误。所以我想出了将cout打印的所有内容写入文件的想法。 问题是,我已经写了很多“cout”。通过整个代码工作并用自定义函数替换每个cout会非常烦人。绕道自定义功能

有没有办法让我可以“挂钩”cout被重定向到我的自定义函数?

+0

“查找并替换...” - >“全部替换”正常工作。只是开玩笑,看看[这里](http://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files)。 – Downvoter

+1

为什么不在命令行上重定向程序的输出,然后解析它? – StoryTeller

回答

3

您可以通过rdbuf方法提供自定义流缓冲区。下面是重定向cout到一个文件中的一个例子:

std::ofstream ofs("output"); 
std::cout.rdbuf(ofs.rdbuf()); 
2

您可以直接重定向标准输出使用命令行与输出重定向

fileneame.exe > log.txt 
    or 
./filename > log.txt 

否则使用一些RAII,类似以下内容到文件:

class Logger 
{ 
    std::ofstream filehandle; 
    std::ostream& myStream; 
    std::streambuf* mySavedStreambuf; 

public: 
    Logger(std::ostream& oldStream, std::string const& filename) 
     : filehandle(filename) 
     , myStream(oldStream) 
     , mySavedStreambuf(oldStream.rdbuf()) 
    { 
     oldStream.rdbuf(filehandle.rdbuf()); 
    } 
    ~Logger() 
    { 
     myStream.rdbuf(mySavedStreambuf); 
    } 
}; 

然后在你的使用/主要程序中做类似的事情:

int main() 
{ 

{ 
     Logger temp(std::cout, "log.txt"); 
     // call funcs that has std::cout, all outputs will be in log.txt 
}// temp goes out of scope, std::cout restored. 

// Call funcs that has std::cout, now all outputs on standard ouput. 

}