在C++中一次将矢量值写入多个文件
Write vector values into multiple files at once in C++
我的向量中有数据。我正在尝试将每个向量值写入,例如将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。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到