如何从序列化数组读取?

时间:2019-04-09 22:53:00

标签: arrays serialization boost

当我序列化单个字符串时。我可以在我的代码中使用它。但是,当我对数组执行相同的操作时,它只会给我随机字符或整数。我想知道一种如何从包含数组的档案中读取内容的方法。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>


using namespace std;

void CWordSave()
{

    ofstream file("archive.txt");
    boost::archive::text_oarchive oa(file);
    string Cwords[] = { "Oak", "Tree", "Dog", "Cat", "Human", "Food", "Computer", "Inteligent", "Special", "Unique" };

    oa << Cwords;
}

void CWordLoad(int &i)
{

    ifstream file("archive.txt");
    boost::archive::text_iarchive ia(file);
    string Cwords;
    ia >> Cwords;


        cout << Cwords[i] << endl;


}
int main()
{
CWordSave();

for (int i = 0; i < 10; ++i)
    {

        CWordLoad(i);

    }

return 0;
}

我希望打印整个数组的内容,而不是随机整数和字符。

1 个答案:

答案 0 :(得分:0)

string Cwords[] = { "Oak", "Tree", "Dog",

是一个数组,通过

oa << Cwords;

您序列化了阵列。

string Cwords;

string的一个实例。通过ia >> Cwords;,您反序列化了一个字符串对象,而不是数组。

cout << Cwords[i] << endl;中,您正在呼叫string::operator[],并且您要访问字符串的单个字符,而不是打印整个字符串实例。

反序列化时,您必须创建数组,并且必须确保其大小足以存储数据:

string Cwords[10];
ia >> Cwords;
cout << Cwords[i] << endl; // now, this accesses instance of string from array

如果您希望代码更加灵活,也许应该使用字符串向量?

#include <boost/serialization/vector.hpp>
...
    vector<string> Cwords = { "Oak", "Tree", "Dog", "Cat", "Human", "Food", "Computer", "Inteligent", "Special", "Unique" };
    oa << Cwords;
...
    vector<string> Cwords;
    ia >> Cwords;

    if (i < Cwords.size())
        cout << Cwords[i] << endl;