我一直在试图编写一个简短的程序,允许用户添加条目到“数据库”,列出他们已经放入的条目,并且能够清除所有条目而无需结束该程序。下面是我得到了创建和清除结构数组
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct BIRTH
{int month; int year;};
struct ID
{string name; bool vip; float score;
struct BIRTH date;} ;
int main(int argc, char** argv) {
ID **ptrarr;
ptrarr = new ID * [10];
for (int r=0; r<10; r++)
{ptrarr[r] = new ID[1] ;}
int counter = 0;
while(counter<100){
cout << "Type add to create a new entry" << endl;
cout << "Type list to see all entries" << endl;
cout << "Type clear to delete all entries" << endl;
cout << "Type exit to terminate" << endl;
string command = "0";
getline (cin,command);
if(command=="add")
{
cout << "Enter name" << endl;
getline (cin,ptrarr[counter][1].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> ptrarr[counter][1].vip;
cout << "Enter score" << endl;
cin >> ptrarr[counter][1].score;
cout << "Month of birth" << endl;
cin >> ptrarr[counter][1].date.month;
cout << "Year of birth" << endl;
cin >> ptrarr[counter][1].date.year;
counter++;
}
else if(command=="list")
{
for (int i=0; i<counter; i++)
{int n=i+1;
cout << n << " "
<< ptrarr[i][1].name << " ";
if (ptrarr[i][1].vip)
{cout << "VIP ";}
cout << "Score: " << ptrarr[i][1].score << " "
<< "Born: " << ptrarr[i][1].date.month << "/" << ptrarr[i][1].date.year << endl;
}
}
else if(command=="clear")
{delete[] ptrarr;
cout << "Entries cleared" << endl;}
else if(command=="exit")
{return 0;}
else
cout << "try again" << endl;
}
return 0;
}
现在,这里的交易:将以下代码编译成功,但是当我在“添加”命令类型,程序崩溃(成就解锁,没想到有可能获得用这么短的代码)。最重要的是该数组由多种类型的结构组成,并且“清除”命令清除了数组中的所有条目。
注意:我知道有一千个更好的方法来编写这段代码,但是我正在写它来练习我迄今为止关于C++所介绍的内容。所以,除非它是绝对必要的代码运行,请不要引入任何新的噱头=)
真的很有帮助=)现在我知道究竟是什么导致代码崩溃。此外,从数组中删除每个条目的好处。我的直觉告诉我,这是我应该做的,但我不知道如何。我现在所做的是,该选项清除条目,而不是数组作为整体,重置计数器,然后再次创建数组,使用与主开头相同的代码 – Quit