gpt4 book ai didi

c++ - 使用 ostream_iterator 的简单文件写入创建文件,但不写入

转载 作者:行者123 更新时间:2023-11-28 05:13:12 24 4
gpt4 key购买 nike

我有一个非常简单的代码来创建一个名为“Input.txt”的文本文件,并使用 ostream_iterator 写入它:

using namespace std;


int main()
{
ofstream os{ "Input.txt" };
ostream_iterator<int> oo{ os,"," };

vector<int> ints;
for (int i = 0; i < 1000; i++)
{
ints.push_back(i);
}

unique_copy(ints.begin(), ints.end(), oo);

system("PAUSE");
return 0;
}

上面的代码创建了一个“Input.txt”,但没有写入任何内容。我是否遗漏了一些非常明显和基本的东西?

最佳答案

在调用 system() 之前,您没有将流刷新到磁盘。

您可以显式flush()close() 流:

int main() {
ofstream os{ "Input.txt" };
ostream_iterator<int> oo{ os,"," };

vector<int> ints;
for (int i = 0; i < 1000; i++) {
ints.push_back(i);
}

unique_copy(ints.begin(), ints.end(), oo);

os.close();

system("PAUSE");
return 0;
}

或者您可以在流周围放置范围括号,以便它更快地超出范围。

int main() {
{
ofstream os{ "Input.txt" };
ostream_iterator<int> oo{ os,"," };

vector<int> ints;
for (int i = 0; i < 1000; i++) {
ints.push_back(i);
}

unique_copy(ints.begin(), ints.end(), oo);
}

system("PAUSE");
return 0;
}

关于c++ - 使用 ostream_iterator 的简单文件写入创建文件,但不写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43152235/

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