C ++输入输出流 [英] C++ input output stream

查看:94
本文介绍了C ++输入输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用cout将输出重定向到文件?

how can we redirect output to files using cout?

推荐答案

这取决于...您要通过编程方式还是从程序外部进行操作?如果要在程序外部执行此操作,则可以像使用其他任何程序一样使用管道.

从程序内部,您需要将流缓冲区cout点替换为一个文件.一种选择是打开要重定向到的文件,然后在cout和文件之间交换流缓冲区.但是我有点懒,所以我会让你弄清楚如何进行交换...

更常见的是,您将需要重定向整个程序的输出.在这种情况下,它会更简单:

It depends... Do you want to do it programmatically or from outside the program? If you want to do it outside the program then you can use pipes as you would for any other program.

From inside the program you need to replace the stream buffer cout points at to a file. One option is to open the file you want to redirect to and then swap the stream buffers between cout and the file. However I''m a bit lazy so I''ll let you figure out how to do the swap...

More commonly you''ll want to re-direct output for the entire program. In this case it''s a bit simpler:

std::ofstream output( "c:\\output.txt" );
std::cout.rdbuf( output.rdbuf() );

std::cout << "Urgle!" << std::endl;



将在文件c:\ output.txt中写入"Urgle!\ n".

需要考虑的事情是,您不应该这样做.如果您使用std :: istream和std :: ostream编写代码,那么您将对读取和写入的位置进行参数化.这使您的代码更加实用:



Will write "Urgle!\n" to the file c:\output.txt.

On thing to consider is that you shouldn''t bother doing this. If you write your code using std::istream and std::ostream then you parameterise where you read from and write to. This makes your code far more usable:

void write_urgle( std::ostream &output )
{
    output << "Urgle!" << std::endl;
}

int main()
{
    std::ofstream output( "c:\\output.txt" );
    write_urgle( output );
}




从长远来看,将具有相同的效果,并且具有更高的可重用性.例如,您可以对write_urgle进行单元测试,而不能(轻松地)对直接使用cout的代码进行单元测试.

嗯,就是这样!玩得开心!

干杯,

Ash




will have the same effect and be a bit more reusable in the long run. For example you can unit test write_urgle while you can''t unit test (easily) code that uses cout directly.

Er, that''s it! Have fun!

Cheers,

Ash


尝试仅将printf更改为cout<<

http://support.microsoft.com/kb/58667 [
try this only change printf to cout <<

http://support.microsoft.com/kb/58667[^]


这篇关于C ++输入输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆