C++ 如何在结构数组中引入值?(c+;+;)

C++ 如何在结构数组中引入值?(c+;+;),c++,struct,C++,Struct,我想做一个程序,让用户输入未知数量的汽车的品牌、价格和颜色,但不知道如何做,或者我必须搜索什么才能理解 我想让它做的例子:我想要20辆车,我想为每辆车输入值,最后让程序说出哪个品牌最贵 #include <iostream> using namespace std; struct car{ char brand[50]; char color[60]; unsigned short int price; }; void compare(car a,

我想做一个程序,让用户输入未知数量的汽车的品牌、价格和颜色,但不知道如何做,或者我必须搜索什么才能理解

我想让它做的例子:我想要20辆车,我想为每辆车输入值,最后让程序说出哪个品牌最贵

#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;
}
#包括
使用名称空间std;
结构车{
char品牌[50];
炭色[60];
无符号短整数价格;
};
无效比较(a车、b车){
如果(a.价格>b.价格)

cout您的第一步是:

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;
    }
}
intmain()
{
汽车m[20];//要做得更好:std::vector
对于(int i=0;i<20;i++)
{
cout>m[i].brand;cout m[i].color;cout m[i].price;cout如果创建名为m1,m2的对象(类型为car),然后希望向其字段中添加一些值,则必须动态创建该对象,因此:

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

我现在更喜欢Java,所以我对语法不是100%确定,但这个概念似乎是正确的。希望它能工作!;-)

C++
有一个字符串类型。使用它。不使用它会以眼泪告终。是的。试着坚持用户现有的代码std::vector到底做什么?@MarkRoberts它也会结束更多的习得知识(如果有足够的毅力)这是一件好事。嗯,更好的方法是在
car
结构中重载
操作符>>
。这将封装数据并使读取更简单。无论如何,字符数组可能会引起麻烦,所以正如其他人所说,最好使用字符串替代;-)这里不需要使用
new
,也不需要任何动态分配。为什么?那么如何在程序运行时向字段添加值呢?
car m1;cin>>m1.brand;
如果不起作用,那么您的代码也不起作用。我的意思是您可以这样做,但您也不会在执行倒立时使用链锯,因为这是可能的在原则上,你被标记为C++,更喜欢使用“代码> STD::String < /代码>文本代替字符数组。字符数组可以溢出,并且必须管理内存。 STD::String 为你管理内存,必要时扩展。