cpp:example0
國立屏東大學 資訊工程學系 物件導向程式設計
1. 實例演練
本範例使用動態的字串陣列來管理不定個數的字串。其中,每當所配置的空間不足時,隨即為其額外配置3個字串的空間。當使用者輸入d時,則將所有字串內容清除。此題的執行結果可參考如下:
執行結果1
輸入
i test 1 i test 2 l i test 3 i test 4 l d l i test 1 d l q
輸出
[test 1][test 2] [test 1][test 2][test 3][test 4] The box is empty! The box is empty! Bye.
執行結果2
輸入
d q
輸出
Nothing to delete! Bye.
執行結果3 輸入
l q輸出
The box is empty! Bye.執行結果4 輸入 q
輸出 Bye.
請參考下面的程式碼:
#include <iostream>
#include <string>
using namespace std;
void insertString();
void listStrings();
void deleteStrings();
int size=0;
string *sBox=NULL;
int main()
{
bool quit=false;
char cmd;
while(!quit)
{
cin >> cmd;
cin.get();
switch(cmd)
{
case 'l': case 'L':
listStrings();
break;
case 'd': case 'D':
deleteStrings();
break;
case 'i': case 'I':
insertString();
break;
case 'q': case 'Q':
quit=true;
if(size!=0)
delete [] sBox;
break;
}
}
cout << "Bye." << endl;
}
void insertString()
{
string *sBoxTemp;
string temp;
getline(cin, temp);
if(size%3==0)
{
sBoxTemp = new string [size+3];
for(int i=0;i<size;i++)
{
sBoxTemp[i]=sBox[i];
}
if(sBox!=NULL)
delete [] sBox;
sBox=sBoxTemp;
}
sBox[size++]=temp;
}
void listStrings()
{
if(size!=0)
{
for(int i=0;i<size;i++)
{
cout << "[" << sBox[i] << "]";
}
cout << endl;
}
else
{
cout << "The box is empty!" << endl;
}
}
void deleteStrings()
{
if(size!=0)
{
size=0;
if(sBox!=NULL)
{
delete [] sBox;
sBox=NULL;
}
}
else
{
cout << "Nothing to delete!" << endl;
}
}
cpp/example0.txt · 上一次變更: 2020/04/01 03:07 (外部編輯)
