我正在運行該程序,但每次退出並再次運行時,矩陣數據[]中的所有數據都將丟失。有沒有辦法保存這些數據,所以當我再次運行它時,我可以檢查它嗎? (很抱歉,如果這個問題太簡單了,我已經開始編碼幾個星期前)存儲數據struct
#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 << "\n\n==============================================================\n\n";
cout << "Thanks for using Restaurant Interface! See you soon mate!" << endl;
exit(0);
default:
cout << "\nInvalid option. please choose again\n";
}
cout << "\n\n==============================================================\n\n";
}
system("PAUSE");
return 0;
}
void inputData()
{
cout << "\n\n==============================================================\n\n";
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 << "\n\n==============================================================\n\n";
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;
}
}
所以你的意思是你想要將你的輸入序列化到一個文件,並從你的程序的另一個運行中恢復(反序列化)它們? –
每次啓動一個程序並初始化一個變量時,它都會存儲在您的內存中。當變量超出範圍或者你簡單地退出程序時,你的變量將從內存中清除。如果你想保留你的數據,你需要將它存儲在一個文件中。 – ppsz
請發佈[mcve],重點放在*「最小」*。 –