0

I want to make a program that lets the user input the brand, price and color of a car for an unknown amount of cars, and cant figure out how to do that or what i have to search for in order to understand.

Example of what i want it to do: i want 20 cars, and i want to input values for each one of them and at the end have the program say which brand is the most expensive.

#include <iostream>

using namespace std;

struct car{

    char brand[50];
    char color[60];
    unsigned short int price;

};

void compare(car a, car b){
    if(a.price > b.price)
        cout << "Most expensive: " << a.brand;
    else
        cout << "Most expensive: " << b.brand;
}

int main()
{
    car m1, m2;
    cout << "Brand of first car: "; cin >> m1.brand; cout << endl;
    cout << "Color of first car: "; cin >> m1.color; cout << endl;
    cout << "Price of first car: "; cin >> m1.price; cout << endl << endl;

    cout << "Brand of second car: "; cin >> m2.brand; cout << endl;
    cout << "Color of second car: "; cin >> m2.color; cout << endl;
    cout << "Price of second car: "; cin >> m2.price; cout << endl << endl;

    compare(m1, m2);

    return 0;
}
MickeyMoise
  • 259
  • 2
  • 13
  • 1
    Since you tagged as C++, prefer to use `std::string` for text instead of character arrays. Character arrays can overflow and **you** have to manage the memory. The `std::string` manages memory for you, expanding as necessary. – Thomas Matthews May 12 '21 at 17:07

2 Answers2

1

Your first step will be:

int main()
{
    car m[20]; // todo better: std::vector

    for(int i=0; i < 20; i++)
    {
        cout << "Brand of first car: "; cin >> m[i].brand; cout << endl;
        cout << "Color of first car: "; cin >> m[i].color; cout << endl;
        cout << "Price of first car: "; cin >> m[i].price; cout << endl << endl;
    }
}

The next step will be to do something with m[].

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
-1

If you create your object (of type car) named m1, m2 and then you would like to add some values to its' fields, you have to create the object dynamically, so it will be:

car *m1 = new car;
cin >> m1->brand;

I'm more into Java right now, so I'm not 100% sure about the syntax, but the concept seems right. Hope it works! ;-)