首页 > 试题广场 >

设计一个名为car的结构,用它存储下述有关汽车的信息:生产商

[问答题]
设计一个名为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

#include <iostream>
#include <windows.h>
#include <cstring>

using namespace std;
struct car{
    string f;
    int y;
};
int main() {
    
    cout<<"How many cars?\n";
    int n;
    cin>>n;  
    car *p = new car [n];
    
    for(int i=0;i<n;i++){
        cin.get();    //吃掉缓存的回车
        cout<<"Car"<<i+1<<"#:"<<endl;
        cout<<"enter maker:";
        char *a = new char [10];
        int m=0;
        a[m] = cin.get();
        //cout<<"a[0]="<<a[m];
        while(a[m]!='\n'){
            a[++m]=cin.get();
            //cout<<"m="<<m<<" "<<a[m]<<endl;
        }
        a[m] = '\0'; 
        (p+i)->f=a;
        cout<<"enter year:";
        cin>>(p+i)->y;
    }
    cout<<"collection:"<<endl;
    for(int i=0;i<n;i++)
        cout<<(p+i)->f<<" "<<(p+i)->y<<endl;
        
    delete [] p;    
    //system("pause");
    return 0;
}

发表于 2021-04-16 22:41:35 回复(0)
#include <iostream>
struct car {
    char carCompany[21];
    int year;
};
int main(void) {
    using namespace std;
    cout << "请输入有几辆汽车:";
    int num = 0;
    char a[21];
    cin >> num;
    cin.get();
    car* carn = new car[num];
    for (int i = 0; i < num; i++) {
        cout << "第" << i+1 << "辆车\n";
        cout << "请输入汽车生产商:";
        cin.getline((carn+i)->carCompany,20);
        cout << "请输入生产年份:";
        cin >> (carn + i)->year;
        cin.get();
    }
    for (int i = 0; i < num; i++) {
        cout << (carn + i)->year << " " << (carn + i)->carCompany << endl;
    }
}
发表于 2019-11-08 20:47:59 回复(1)