写入终端和文件C ++ [英] Writing to both terminal and file c++
问题描述
我找到了针对Python,Java,Linux脚本而不是C ++的问题:
I found this question answered for Python, Java, Linux script, but not C++:
我想将C ++程序的所有输出都写到终端和输出文件中.使用类似这样的内容:
I'd like to write all outputs of my C++ program to both the terminal and an output file. Using something like this:
int main ()
{
freopen ("myfile.txt","w",stdout);
cout<< "Let's try this";
fclose (stdout);
return 0;
}
仅将其输出到名为"myfile.txt"的输出文件,并阻止其显示在终端上.如何使其同时输出到两者?我使用Visual Studio 2010 Express(如果有帮助的话).
outputs it to only the output file named "myfile.txt", and prevents it from showing on the terminal. How can I make it output to both simultaneously? I use visual studio 2010 express (if that would make any difference).
提前谢谢!
推荐答案
可能的解决方案:使用类似于cout的静态流对象将cout写入文件和文件中.
Possible solution: use a static stream cout-like object to write both to cout and a file.
一个粗略的例子:
struct LogStream
{
template<typename T> LogStream& operator<<(const T& mValue)
{
std::cout << mValue;
someLogStream << mValue;
}
};
inline LogStream& lo() { static LogStream l; return l; }
int main()
{
lo() << "hello!";
return 0;
}
不过,您可能需要显式处理流操纵器.
You will probably need to explicitly handle stream manipulators, though.
这篇关于写入终端和文件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!