关于C++++中字符串、数字交叉输入,内存动态分配等。
分析都在程序里面注释了。
- #include <iostream>
- #include <string>
- struct car {
- std::string make;
- int year;
- };
- int main()
- {
- using namespace std;
- int number;
- /* car * car_num; */
- cout << “How many cars do you wish to catalog? “;
- cin >> number;
- cin.get(); /* 清除换行符 */
- /*按需求动态分配内存,没想到随便一试,竟然能这么用 */
- car * car_num = new car [number]; /* number 是变量 */
- int i;
- for ( i = 0; i < number; i++ )
- {
- /* car_num = new car; */
- cout << “Mark 1 “ << car_num << endl;
- cout << “C++ar #” << i + 1 << “:\n”;
- cout << “Please enter the make: “;
- getline( cin, car_num->make ); /* 支持输入带空格的字符串 */
- cout << “Please enter the year made: “;
- /* cin.clear(); */
- cin >> car_num->year;
- cin.get(); /* 清除换行符,不然下一轮循环getline()会因为换行符输入失败 */
- car_num++;
- cout << “Makr 2 “ << car_num << endl;
- }
- car_num -= i;
- cout << “Mark Start “ << car_num << endl;
- cout << “Here is your collection: “ << endl;
- for ( i = 0; i < number; i++ )
- {
- cout << car_num->year << ” “ << car_num->make << endl;
- car_num++;
- }
- car_num -= i;
- /*删除指针数组,好吧,省了循环了,但是它怎么知道删掉几个? */
- delete[] car_num;
- return(0);
- }