【问题标题】:What am I doing wrong with my serializing a vector with structs in it to a .dat file?将带有结构的向量序列化为 .dat 文件,我做错了什么?
【发布时间】:2009-04-02 11:13:26
【问题描述】:

如果我输入

描述:苹果

数量:10

批发成本:30

零售成本:20

添加日期:12 月

这些是我的 .dat 文件中的内容:

1Apple103020十二月

但是当我加载我的程序时,它没有正确加载结构,导致我的列表中有 0 个项目。这是它应该看起来的样子还是我做错了什么。

代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace System;
using namespace std;
#pragma hdrstop

bool isValidChoice(int size, int choice);

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);

template<typename T>
vector<T> readVector(ifstream &in);

template<typename T>
vector<T> addItem(vector<T> &vec);

template<typename T>
void printItemDescriptions(vector<T> &vec);

template<typename T>
int displayRecord(vector<T> &vec);

struct InventoryItem {
    string Description;
    int Quantity;
    int wholesaleCost;
    int retailCost;
    string dateAdded;
} ;


int main(void)
{
    cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
    ifstream in("data.dat");
    if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl;}
    cout << "Loading data..." << endl;
    vector<InventoryItem> structList = readVector<InventoryItem>( in );
    cout <<"Load complete." << endl << endl;
    in.close();


    while (1)
    {

        string line = "";
        cout << "There are currently " << structList.size() << " items in memory.";
        cout << endl << endl;
        cout << "Commands: " << endl;
        cout << "1: Add a new record " << endl;
        cout << "2: Display a record " << endl;
        cout << "3: Edit a current record " << endl;
        cout << "4: Delete a record " << endl;
        cout << "5: Save current information " << endl;
        cout << "6: Exit the program " << endl;
        cout << endl;
        cout << "Enter a command 1-6: ";

        getline(cin , line);

        int rValue = atoi(line.c_str());

        system("cls");

        ofstream out("data.dat");

        switch (rValue)
        {
            case 1:
                addItem(structList);
                break;
            case 2:
                displayRecord(structList);
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
                writeVector(out , structList);
                break;
            case 6:
                return 0;
            default:
                cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
        }

        out.close();
    }

    system("pause");

    return 0;
}

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
    out << vec.size();

    for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
    {
        out << *i;
    }
    cout << "Save completed!" << endl << endl;
}

ostream &operator<<(ostream &out, const InventoryItem &i)
{
    out << i.Description;
    out << i.Quantity;
    out << i.wholesaleCost << i.retailCost;
    out << i.dateAdded;
    return out;
}

istream &operator>>(istream &in, InventoryItem &i)
{
    in >> i.Description;
    in >> i.Quantity;
    in >> i.wholesaleCost >> i.retailCost;
    in >> i.dateAdded;
    return in;
}



template<typename T>
vector<T> readVector(ifstream &in)
{
    size_t size;
    if (in.fail())
    {
    in >> size;
    } else {
        size = 0;
    }

    vector<T> vec;
    vec.reserve(size);

    for(unsigned int i = 0; i < size; i++)
    {
        T tmp;
        in >> tmp;
        vec.push_back(tmp);
    }

    return vec;
}

template<typename T>
vector<T> addItem(vector<T> &vec)
{
    system("cls");

    string word;
    unsigned int number;

    InventoryItem newItem;

    cout << "-Add a new item-" << endl << endl;
    cout << "Enter the description for the item: ";
    getline (cin , word);
    newItem.Description = word;

    cout << endl;
    cout << "Enter the quantity on hand for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.Quantity = number;

    cout << endl;
    cout << "Enter the Retail Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.retailCost = number;

    cout << endl;
    cout << "Enter the Wholesale Cost for the item: ";
    getline (cin , word);
    number = atoi(word.c_str());
    newItem.wholesaleCost = number;

    cout << endl;
    cout << "Enter current date: ";
    getline (cin , word);
    newItem.dateAdded = word;

    vec.push_back(newItem);

    return vec;
}

template<typename T>
void printItemDescriptions(vector<T> &vec)
{
    int size = vec.size();

    if (size)
    {
        cout << "---------------------------------" << endl;
        cout << "|      ~ Item Descriptions ~    |" << endl;
        cout << "---------------------------------" << endl;
        cout << "*********************************" << endl;
        for (int i = 0 ; i < size ; i++)
        {
            cout << "(" << i+1 << ")" << ": " << vec[i].Description << endl;
        }
        cout << "*********************************" << endl << endl;
    }
}

template<typename T>
int displayRecord(vector<T> &vec)
{
    string word = "";
    string quit = "quit";
    int choice = 1;
    int size = vec.size();

    if (size)
    {
        printItemDescriptions(vec);
        cout << endl;

        while (1)
        {
            cout << "Type \"exit\" to return to the Main Menu." << endl << endl;
            cout << "Enter \"list\" to re-display the items." << endl << endl;
            cout << endl;
            cout << "Pick the number of the item you would like to display: ";
            getline (cin , word);

            if (convertToLower(word) == "exit") { system("cls"); return 0; }
            if (convertToLower(word) == "list") { system("cls"); displayRecord(vec); }

            choice = atoi(word.c_str());

            if (isValidChoice(size, choice))
            {
                system("cls");
                cout << endl << "[Item (" << choice << ") details] " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Description   * " << vec[choice-1].Description << endl;
                cout << "******************" << endl << endl;
                cout << "******************" << endl;
                cout << "*Quantity On Hand* " << vec[choice-1].Quantity << endl;
                cout << "******************" << endl << endl;
                cout << "******************" << endl;
                cout << "* Wholesale Cost * " << vec[choice-1].wholesaleCost << endl;
                cout << "****************** " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Retail Cost   * " << vec[choice-1].retailCost << endl;
                cout << "****************** " << endl << endl;
                cout << "******************" << endl;
                cout << "*  Data Added    * " << vec[choice-1].dateAdded << endl;
                cout << "****************** " << endl << endl;
            } else { system("cls"); cout << "That item doesn't exist!" << endl; cout << "Pick another item or enter \"list\" to see available items." << endl << endl; }
        }
    } else { cout << "There are currently no items to display." << endl << endl; system("pause"); system("cls"); return 0; }

    return 1;
}

bool isValidChoice(int size, int choice)
{
    for (int i = 0 ; i <= size ; i++)
    {
        if (choice == size) { return true; }
    }
    return false;
}

string convertToLower(string word)
{
    for (unsigned int i = 0 ; i < word.size() ; i++)
    {
        word[i] = tolower(word[i]);
    }

    return word;
}

【问题讨论】:

    标签: c++ serialization vector fstream


    【解决方案1】:

    在您的阅读功能中:

       if (in.fail())
    

    应该是:

       if ( ! in.fail())
    

    或者更好:

    int n;
    
    if ( ! (in >> n) ) {
      n = 0;
    }
    

    【讨论】:

    • 我这样做过一次,我得到了矢量太大的错误,因为我的矢量被设置为超过 2000 万的大小等等。如果文件为空白,如何防止它设置 Vectors 大小?
    • 是的,我这样做了,但我遇到了一个致命错误,因为 Size 是几百万。失败没用,我猜对吧?
    【解决方案2】:

    为结构项目使用一些分隔符,例如" "(空格)

    【讨论】:

    • 嗯,我不知道该怎么做。我一直在这几个小时sssss....
    • 你能提供一个例子来说明如何做到这一点吗?
    【解决方案3】:

    同样,序列化是一项不那么简单的任务。如果您可以花时间学习图书馆。

    我不会重新发布我给你上一个问题的answer,但我相信你真的应该看看它。它解释了您面临的一些问题并提供了解决方案。

    【讨论】:

    • 对不起。我确实读过你的链接。我只是想完成我的项目,以便我可以查看它以获得我可以理解的工作参考。我已经在这工作了 15 个小时以上……所以请理解我为什么要在这里问这么多问题。我真的非常感谢你给我的所有帮助。
    • 没关系。希望对你有帮助:)
    【解决方案4】:

    保存 DAT 文件时,您需要在字符串之间添加一个空格(空格/制表符)。

    使用 operator>> 读取字符串时,它会读取一个字符串,直到找到第一个空白字符(空格/制表符/EOL)。

    来自您的代码:

    ostream &operator<<(ostream &out, const InventoryItem &i)
    {
        out << i.Description << ' ';
        out << i.Quantity << ' ';
        out << i.wholesaleCost  << ' ' << i.retailCost  << ' ';
        out << i.dateAdded  << ' ';
        return out;
    }
    

    更新

    即便如此,当使用 operator>> 加载描述时,例如,描述将不完整(加载到保存的描述文本中的第一个空格)。

    【讨论】:

    • 好吧...如果您的描述包含空格...您仍然会遇到加载问题...因为描述加载将仅限于第一个。在我看来,对于序列化/反序列化,您需要更先进的东西。例如,参见 Boost.Serialization。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多