提升输入流错误。如何将 std:vectors 的动态矢量保存为 xml 文件

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

我正在尝试保存

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

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

完整输出为


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

Here 是关于 boost::archive 抛出的异常的参考。 关于 input/output stream error 的以下句子:

Be sure that an output archive on a stream is destroyed before opening an input archive on that same stream.

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