freopen() 等效于 C++ 流

freopen() equivalent for c++ streams(freopen() 等效于 C++ 流)

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

问题描述

当使用 c 风格的 i/o 编程时,我有时会使用 freopen() 重新打开 stdin 以进行测试,这样我就不必一遍又一遍地重新输入输入.我想知道 c++ i/o 流是否有等价物.另外,我知道我可以使用管道在命令行/终端/任何东西上重定向它,但我想知道是否有办法在我的代码中做到这一点(因为如你所见,我对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 也适用于 cincout.无需搜索新内容.

freopen also works with cin and cout. No need to search for 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控制来自与对象stdin关联的流缓冲区的输入,在中声明.

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

所以根据标准,如果我们重定向stdin,它也会重定向cin.cout 反之亦然.

So according to the standard, if we redirect stdin it will also redirect cin. Vice versa for cout.

这篇关于freopen() 等效于 C++ 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:freopen() 等效于 C++ 流

基础教程推荐