題目:設計稱為car的結構,記錄有關汽車的下列資訊:其製造商存在字元陣鬥的字串中,以及製造的年份,為一整數。寫一程式,先詢問使用者有多少汽車要列進目錄,然後用new配置此數量之car結構的動態陣列。再來,提示使用者輸入每一輛車的製造商(可能由一個以上的單字組成)和製造年份。注意,它要交互讀入字串和數字。最後,顯示每一輛汽車的資訊。程式的幸後結果有如下述:
How many cars do you wish to catalog? 2
Car #1:
Please enter the make: Hudson Hornet
Please enter the year made: 1952
Car #2:
Please enter the make: Kaiser
Please enter the year made: 1951
Hereis your collection:
1952 Hudson Hornet
1951 Kaiser

紅色的字為輸入。
原始碼:http://down.gogobox.com.tw/t2329175/qpum2_rpum2
以下兩個程式碼都是用指標做的,但方法有點小差異。
程式碼一:

/*damody car question I like*/ //7/17 #include <iostream> #include <cstring> using namespace std; struct car // structure declaration { char * name; int year; }; char * getname() { char temp[80]; cin.get(temp、80); char * pn = new char[strlen(temp) + 1]; strcpy(pn、temp); return pn; } int main() { int Num; cout << "How many cars do you wish to catalog? "; cin >> Num; cin.get(); car * inf = new car + Num; for (int i = 0;i < Num;i++) { cout << "Car #" << i + 1 << ":" << endl; cout << "Please enter the make: "; cin.get(inf -> name,20); cin.get(); cout << "Please enter the made: "; cin >> (*inf).year; cin.get(); *inf++; } cout << "Here is your collection:\n"; inf -= Num; for (int i = 0;i < Num;i++) { cout << inf[i].year << " " << inf[i].name << endl; } delete inf; return 0; } ==================================================== 程式碼二: /*damody car question I like*/ //7/17 #include <iostream> #include <cstring> using namespace std; struct car // structure declaration { char * name; int year; }; char * getname() { char temp[80]; cin.get(temp、80); char * pn = new char[strlen(temp) + 1]; strcpy(pn、temp); return pn; } int main() { int Num; cout << "How many cars do you wish to catalog? "; cin >> Num; cin.get(); car * inf = new car[Num]; for (int i = 0;i < Num;i++) { cout << "Car #" << i + 1 << ":" << endl; cout << "Please enter the make: "; inf[i].name = getname(); cin.get(); cout << "Please enter the made: "; cin >> inf[i].year; cin.get(); } cout << "Here is your collection:\n"; for (int i = 0;i < Num;i++) { cout << inf[i].year << " " << inf[i].name << endl; } delete inf; return 0; }

讓地獄深紅的天亮 發表在 痞客邦 PIXNET 留言(0) 人氣()