简体   繁体   中英

C++ Dynamic Array of Structures User Input

I'm trying to learn C++ on my own using Stephen Prata's "C++ Primer Plus 6th Edition. One of the chapter 5 exercises asks me to design a dynamic structure holding name and year of a number of cars. All this information is to be input by the user. My questions are:

1) Can I use a string object instead of an array of char in the structure? If so, could you tell me how?

2) How can I enable the user to input a name that consists of more than one word? I've been trying to use get(), getline() etc. but I just can't make it work.

3) I know it is a simple programme but in what way could the code be improved?

Thank you in advance.

#include<iostream>
using namespace std;

const int ArSize = 20;

struct automobile
{
    char name[ArSize];
    int year;
};

int main()
{
cout << "How many cars do you wish to catalogue?\n";
int number;
cin >> number;

automobile * car = new automobile[number];
int n = 0;

while (n < number)
{
    cout << "Car #" << n+1 << ":\n";
    cout << "Please enter the make: ";
    cin >> car[n].name; cout << endl;

    cout << "Please enter the year: ";
    cin >> car[n].year; cout << endl;
    n++;
}

    cout << "Here is your collection:\n";

int m = 0;
while (m < number)
{
    cout << car[m].year << " " << car[m].name << endl;
    m++;
}
delete [] car;
return 0;
}

1) Can I use a string object instead of an array of char in the structure? If so, could you tell me how?

Yes, simply provide a member variable of type std::string :

struct automobile
{
    std::string name;
    int year;
};

2) How can I enable the user to input a name that consists of more than one word? I've been trying to use get(), getline() etc. but I just can't make it work.

Use std::getline() :

cout << "Please enter the make: ";
std::getline(std::cin,car[n].name); cout << endl;

3) I know it is a simple programme but in what way could the code be improved?

Such questions are better asked at SE Code Review , as soon you have working code. For Stack Overflow this often simply renders as too broad .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM