freopen函数()相当于C ++流 [英] freopen() equivalent for c++ streams

查看:153
本文介绍了freopen函数()相当于C ++流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在与C风格的编程I / O我有时用freopen函数()重新用于测试标准输入,这样我就不必一遍遍重新键入输入。我在想,如果有一个C ++的I / O流的等效。另外,我知道我可以用管道重定向的命令行/终端/ whateveritis,但我不知道是否有办法做到这一点我的code里面(因为你可以看到,我不是很知识渊博的有关CL / T / W)。

When programming with c-style i/o I sometimes use freopen() to reopen stdin for testing purposes so that I don't have to retype the input over and over. I was wondering if there is an equivalent for c++ i/o streams. Also, I know that I can use pipes to redirect it on the command line/terminal/whateveritis but I was wondering if there was a way to do it inside my code (because as you can see, I'm not very knowledgeable about the cl/t/w).

推荐答案

freopen函数与也适用CIN COUT 。无需寻找新的东西。

freopen works also with cin, cout. No need for searching something new.

freopen("input.txt","r",stdin);//redirects standard input
freopen("output.txt","w",stdout);//redirects standard output

int x;
cin>>x;//reads from input.txt
cout<<x<<endl;//writes to output.txt

编辑:从C ++标准27.3.1:

From C++ standard 27.3.1:

这与对象标准输入关联的流缓冲区,在宣布CIN控制输入对象&LT; cstdio方式&gt;

The object cin controls input from a stream buffer associated with the object stdin, declared in <cstdio>.

因此​​按照标准,如果我们重定向标准输入它也将重定向 CIN 。关于同样的事情COUT

So according standard if we redirect stdin it will redirect also cin . Same thing about cout.

这篇关于freopen函数()相当于C ++流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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