存储数据结构

Storing data struct

本文关键字:数据结构 存储      更新时间:2023-10-16

我运行这个程序很好,但是每次我退出它并再次运行时,矩阵 data[] 中的所有数据都会丢失。有没有办法保留这些数据,以便当我再次运行它时可以检查它?(对不起,如果这个问题太简单了,我几周前就开始编码了)

#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <cstdio>
#include <iomanip>
using namespace std;
const int TRUE = 1;
static int n = 0;

struct Restaurant{
    char name[30];
    char address[50];
    float price;
    char food[20];
};
Restaurant data[10];
void inputData(void);
void outputData(void);
    int main()
{
    char option;
    cout << "============Welcome to Restaurant Interface!============n" << endl;
    while(TRUE)
    {
        cout << "Type 'A' to add a restaurant data " << endl;
        cout << "     'S' to search for restaurants "<< endl;
        cout << "  or 'E' to exit" << endl;
        option = getch();
        switch (option)
        {
            case ('a'):
            case ('A'):             
                inputData();
                break;
            case ('s'):
            case ('S'):
                outputData();
                break;
            case ('e'):
            case ('E'):
                cout << "nn==============================================================nn";
                cout << "Thanks for using Restaurant Interface! See you soon mate!" << endl;
                exit(0);
            default:
                cout << "nInvalid option. please choose againn";                  
        }
        cout << "nn==============================================================nn";
    }
    system("PAUSE");
    return 0;
}
void inputData()
{
    cout << "nn==============================================================nn";
    char temp[80];
    cout << "Type the name of your restaurant: "; gets(data[n].name);
    cout << "Type the address of your restaurant: "; gets(data[n].address);
    cout << "Type the price range: "; gets(temp);
    data[n].price = atof(temp);
    cout << "Type the style of food: "; gets(data[n].food);;
    cout << "New restaurant data added successfully!!!" << endl;
    n++;    
}
void outputData()
{
    cout << "nn==============================================================nn";
    if(!n)
    {
        cout << "Empty list." << endl;
        return;
    }
    cout << "Restaurant list" << endl;
    cout << left << setw(20) << "Name";
    cout << left << setw(30) << "Address";
    cout << left << setw(15) << "Average Price";
    cout << left << setw(10) << "Type of cuisine" << endl;
    for (int i=0; i<n; i++)
    {
        cout << left << setw(20) << data[i].name;
        cout << left << setw(30) << data[i].address;
        cout << "R$" << left << setw(15) << data[i].price;
        cout << left << setw(10) << data[i].food << endl;
    }
}

程序不保留在不同运行之间存储在其本地内存中的任何可访问数据。

声明全局数据,如

Restaurant data[10];

不能克服此限制。全局将在程序的每次新运行时实例化和初始化,从以前的运行中收集的数据将丢失。

如果要保留该数据,则需要具有某种持久性机制,例如将数据反序列化为文件或数据库表/从文件或数据库表反序列化。

C++程序

完成执行时擦除每个数据。如果要保存程序执行期间创建的信息,最简单和更简单的方法是使用数据文件。以下是有关以下方面的一些信息