gpt4 book ai didi

c++ - 在变量中切换文件 (cpp)

转载 作者:行者123 更新时间:2023-11-28 02:16:55 25 4
gpt4 key购买 nike

我的问题最好用代码来解释:

fstream One;
fstream Two;
fstream Three;
One.open(path1, ios_base::out);
Two.open(path2, ios_base::out);
Three.open(path3, ios_base::out);

正如您在上面看到的,我有三个 fstream 变量,并且我已经将三个单独的文件加载到它们中。现在我想更改一些文件。

One=Three;
Three=Two;

因此,当我使用一个文件时,我将使用路径 3 中的文件。我知道我可能不能那样分配 fstreams。这是我的问题:我该怎么做?对不起我的英语,如果有什么不清楚,请发表评论。提前致谢!

最佳答案

#include <algorithm>
#include <fstream>
using namespace std;

auto main() -> int
{
auto path1 = "a.txt";
auto path2 = "b.txt";
auto path3 = "c.txt";

ofstream one;
ofstream two;
ofstream three;
one.open(path1);
two.open(path2);
three.open(path3);

swap( one, two );
two << "Two" << endl;
}

注意事项:

  • ofstream 用于纯输出流。
  • 不要使用全局变量。
  • 理想情况下检查故障(在上面的代码中没有完成)。

关于c++ - 在变量中切换文件 (cpp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33777766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com