我一直在試圖編寫一個簡短的程序,允許用戶添加條目到「數據庫」,列出他們已經放入的條目,並且能夠清除所有條目而無需結束該程序。下面是我得到了創建和清除結構數組
#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