Practice make perfect.
Chapter 5 exercise 6:
problem description:
设计一个名为car的结构,用它存储下述有关汽车的信息:生产商(存储在字符数组或string对象中的字符串)、生产年份(整数)。编写一个程序,向用户请问有多少辆汽车。随后,程序使用new关键字来创建一个由相应数量的car结构组成的动态数组。接下来程序提示输入每辆车的生产商(可由多个单词组成)和年份信息。请注意,这里需要特别小心,因为它将交替读取数值和字符串。最后,程序将显示每个结构的内容。
#include<iostream> #include<string> /*string I/O*/ using namespace std; struct Car { string provider; int year; }; int main() { int total_num = 0; cout << "How many cars do you wish to catalog ? " ; cin >> total_num; /*allocate the dynamic struct*/ Car* car = new Car[total_num]; /*read I/O and save it*/ for (int i = 0; i < total_num; ++i) { char ch; cout << "Car # "<< i+1 << endl; cout << "Please enter the provider : "; /*getchar() read Enter to exit, used for clearing the Enter input*/ getchar(); getline(cin, car[i].provider); cout << "Please enter the made year : " ; cin >> car[i].year; } /*traverse the struct*/ cout << "Here is your collection : " << endl; for (int i = 0; i < total_num; ++i) { cout << car[i].year << " " <<car[i].provider << endl; } /*release the space*/ delete[] car; return 0; }