我正在运行这个程序,但每次退出并再次运行时,矩阵数据[]中的所有数据都将丢失。有没有办法保留这些数据,所以当我再次运行它时,我可以检查它吗? (对不起,如果这个问题太简单了,我几周前就开始编码了)
#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;
}
}
答案 0 :(得分:0)
程序不允许在不同的运行之间保存存储在本地内存中的任何数据。
声明全局数据,如
Restaurant data[10];
没有克服这个限制。全局将在程序的每次新运行时进行实例化和初始化,从以前的运行中收集的数据将丢失。
如果要保留该数据,则需要使用某种持久性机制,例如将数据从/或序列化到文件或数据库表中。
答案 1 :(得分:0)
C ++在程序完成执行时擦除每个数据。如果要保存在执行程序期间创建的信息,最简单和最简单的方法是使用数据文件。 Here is some information about