freopen() 等效于 C++ 流

2023-10-18C/C++开发问题
1

本文介绍了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++ 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6