提升输入流错误.如何将标准:矢量的动态矢量另存为 XML 文件

boost input stream error. how to save dynamic vector of std:vectors as xml file

本文关键字:动态 另存为 文件 XML 标准 输入流 错误      更新时间:2023-10-16

我正在尝试保存一个

vector<vector<int>> 

作为 XML 文件。矢量将动态调整大小。我尝试使用BOOST:SERIALIZATION但我收到此错误。 libc++abi.dylib:终止时出现 boost::archive::archive_exception 类型的未捕获异常:输入流错误

我看不出我的代码有任何问题。如果有人可以建议,除了 boost 之外的另一种另存为 xml 的方法对我来说很好。


#include <iostream>
#include <vector>
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;

int main() {
    using namespace std;
    int numChords;
    vector<vector<int> > chords; // array to store chord arrays
    numChords = 2; // size of outer array
    chords = {{41, 48, 55, 56, 58, 63},
              {44, 51, 56, 58, 61, 63}}; // data structure
    // print the array
    cout << endl << "you entered: " << endl;
    // print the results
    for (int i = 0; i < numChords; i++) {
        for (int j = 0; j < chords[i].size(); j++) {
            cout << chords[i][j] << ",";
        }
        cout << endl;
    }
    // store the array to a file
    std::ofstream ofs("dump.dat");
    boost::archive::text_oarchive oa(ofs);
    oa & chords;
    chords.clear(); // clear the original array
    // restore the array from the file
    std::ifstream ifs("dump.dat");
    boost::archive::text_iarchive ia(ifs);
    ia & chords;
    cout << endl << "you saved: " << endl;
    // print the restored array
    for (int i = 0; i < numChords; i++) {
        for (int j = 0; j < chords[i].size(); j++) {
            cout << chords[i][j] << ",";
        }
        cout << endl;
    }
    return 0;
}

我尝试了各种不同的文件名和文件路径。我尝试在提升语句后使用 & 或 <<>>。

全输出为


you entered: 
41,48,55,56,58,63,
44,51,56,58,61,63,
libc++abi.dylib: terminating with uncaught exception of type boost::archive::archive_exception: input stream error
Process finished with exit code 6

提前感谢您的任何建议。

肖恩

大括号将流中的输出和输入操作括起来:

{ //<--
  // store the array to a file
  std::ofstream ofs("dump.dat");
  boost::archive::text_oarchive oa(ofs);
  oa & chords;
}
chords.clear(); // clear the original array
{ // <--
  // restore the array from the file
  std::ifstream ifs("dump.dat");
  boost::archive::text_iarchive ia(ifs);
  ia & chords;
}

以下是有关 boost::archive 引发的异常的参考。下面这句话关于input/output stream error

确保在打开之前销毁流上的输出存档 同一流上的输入存档。

如果不满足此条件,则会出现异常。