【问题标题】:Write vector values into multiple files at once in C++在 C++ 中一次将向量值写入多个文件
【发布时间】:2020-02-18 04:52:09
【问题描述】:

我的向量中有数据。我正在尝试将每个向量值,例如 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++ 的基础知识并尝试学习高级概念。 谢谢

【问题讨论】:

  • output_file[80] 是该数组末尾的一个元素。数组的第一个元素是output_file[0],数组的最后一个元素是output_file[79]。
  • 使用to_string 将数字转换为字符串不会将其转换为英文单词,它会生成一串十进制数字字符。整数值0 变为字符串"0" 而不是字符串"zero"。
  • 您在打开文件后立即关闭所有文件,ostream_iterator 不适用于迭代多个流。您是否尝试过编写一个简单的循环来索引output_file 和rowname?
  • @walnut 请注意,写入已关闭的流实际上并不会崩溃。 (尽管这样做几乎可以肯定不是本意,所以显然仍然是一件值得指出的好事情。)

标签: c++ vector ofstream


【解决方案1】:

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

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?
}

写入已关闭的 ofstream 不会使程序崩溃,但会在 ofstream (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强>。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2013-07-02
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2023-03-06
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多