在C++中一次将矢量值写入多个文件

Write vector values into multiple files at once in C++

本文关键字:文件 C++ 一次      更新时间:2023-10-16

我的向量中有数据。我正在尝试将每个向量值写入,例如将vector_name[0]写入"examplezero.h",vector_name[1]写入"exampleone.h",依此类推。下面的代码显示了我如何创建文件。

int co = 80;
string name ="example";
std::ofstream output_file[80];
for (int i = 0; i < co; i++)
{
output_file[i].open(name + std::to_string(i) + ".h");
output_file[i].close();
}

我正在尝试迭代我的向量并尝试写入我的文件。

std::vector<string> rowname;  //This has all the values
for (auto i = rowname.begin(); i != rowname.end(); ++i) 
{
std::ostream_iterator<std::string> 
output_iterator(output_file[80], "n");
std::copy(rowname.begin(), rowname.end(), output_iterator);
}

当我尝试写入文件时,它崩溃了。你能告诉我出了什么问题吗?我知道C++的基础知识,并试图学习高级概念。 谢谢

您的程序可能崩溃,因为您编写了以下代码:

std::ostream_iterator<std::string> 
output_iterator(output_file[80], "n");

output_file[80]是数组末尾的一个元素。 您将其声明为:

std::ofstream output_file[80];

该数组的第一个元素是output_file[0],该数组的最后一个元素是output_file[79]

还有更多不对劲的地方

正如@walnut指出的那样,如果你的代码真的和你发布的那样,那么它似乎在打开每个文件后立即关闭它,而不会向文件写入任何内容。

for (int i = 0; i < co; i++)
{
output_file[i].open(name + std::to_string(i) + ".h");
output_file[i].close(); // Leaving so soon?
}

写入已关闭的流不会使程序崩溃,但会在流(badbit)上设置错误条件。 因此,这对你来说似乎是一个无声的失败。

要修复

要解决您的问题,您必须在打开文件之后但在关闭文件之前写入文件。

您还必须准确确定实际要写入哪个output_file并提供正确的数组索引。 从示例代码中不清楚您的意图是什么。 您必须决定要将rowname向量的每个元素写入哪个文件(您打开的 80

个文件)。您编写std::copy会将rowname向量中的所有字符串写入同一流。 如果您的目的是将每个元素写入其自己的文件,则必须以不同的方式对其进行设置。

更多类似的东西:

#include <fstream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> rowname = { "alpha", "bravo", "charlie" }; // example data
std::string name = "example"; // base filename
for (size_t i = 0; i < rowname.size(); ++i) {
std::ofstream output_file;
std::string filename = name + std::to_string(i) + ".h"; // e.g.: "example0.h"
output_file.open(filename);
output_file << rowname[i]; // write the string to the file
output_file.close(); // if you want
}
}

这会将文本alpha写入example0.h,bravo写入example1.h,charlie写入example2.h