第二天打卡第一个问题

发布时间 2023-04-13 15:01:44作者: 序章0

问题描述:设计一个名为car的结构,用它存储下述有关汽车的信息:生产商(存储在字符数组或string对象中的字符串)、生产 年份(整数)。编写一个程序,向用户询问有多少车辆。随后,程序使用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

Here is your collection:

1952 Hudson Hornet

1951 Kaiser 

解决思路:1.建立一个结构体,其中有两个成员,一个是string数组存储生产商,另一个是int类型存储生产年份

2.向用户询问有几辆车存储进一个变量中

3.使用for循环,循环次数是上面存进变量的数值

4.循环体中向用户提出两个问题,输入生产商存储进string数组中,输入生产年份存储进int整型中

5.输出语句Here is your collection:接着打印出刚刚存储进string数组和int整型中的数据。

代码:

#include <iostream>
#include<string>
using namespace std;
int main()

{
int n;
struct car
{
string a;
int y;
};
cout << "How many cars do you wish to catalog?";
cin >> n;
car* c = new car[n];
for (int i = 0; i < n; i++)
{
cout << "Car #" << i + 1<<endl;
cout << "Please enter the make :";
getline(cin,c[i].a);
getline(cin, c[i].a);
cout << "Please enter the year made:";
cin >> c[i].y;
}
cout << "Here is your collection:"<<endl;
for (int i = 0; i < n; i++)
{
cout << c[i].y << " ";
cout<< c[i].a;
cout << endl;
}
return 0;
}