如何在c++中迭代类对象的字符串变量

How to iterate over string variables of a class object in C++?

本文关键字:对象 字符串 变量 迭代 c++      更新时间:2023-10-16

这里我有一个Car的类定义,然后我用它创建一个carObject。我希望用户为carObject中的所有变量输入值。正如您在这里看到的,我已经设法获得了用户输入,但是我认为我解决这个问题的方法是低效的。

我注意到除了第一个之外,所有的用户输入都非常相似。我想使用某种循环来迭代声明语句或语句块,并每次更改变量。我想放一个if语句,只为循环的第一次迭代输入不同的输入。我知道在bash中可以使用字符串变量来表示变量名,但我不知道在c++中是否可以。

注意,对象的名称没有改变,只有与之关联的变量改变了。对于用户输入,我也使用了相同的词,最好在每次迭代中都进行更改。我也有一系列类似命名的数组。这些数组的目的是告诉用户特定变量有哪些选项可用。

虽然我以前有编程经验,但我对c++还是比较陌生的。一段代码可以作为我的问题的解决方案,其中包含对另一个函数的调用,这符合我的目的。下面是我的代码。

    #include <iostream>
    #include <string>
    using namespace std;
    class Car {
    public:
    string Name;
    string Model;
    string Color;
    string Transmission;
    string Category;
    };
    int main() {
    Car CarObject;
    string modelOptions [3] = { "Ferrari", "Porsche", "Nissan" };
    string colorOptions [4] = { "Blue", "Red", "Green", "White" };
    string transmisionOptions [2] = { "Automatic", "Manual" };
    string categoryOptions [3] = { "A", "B", "C" };
    cout << "Enter " << "name" << " for Car 1." << endl;
    cin >> carObject.Name;
    cout << endl;
cout << "Enter " << "model" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: modelOptions) {
    cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Model;
cout << endl;
cout << "Enter " << "color" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: colorOptions) {
    cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Color;
cout << endl;
cout << "Enter " << "transmission" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: transmissionOptions) {
    cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Transmission;
cout << endl;
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
    cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
...
return 0;
}
void Car::InputParameter(string& param, const string &msg, const vector<string>& options)
{
    cout << msg << endl;
    for (const string &text: options) {
          cout << " " << text;
    }
    cout << "." << endl;
    cin >> param;
    cout << endl;
}
我想你可能会想要这样的东西。

这段代码:

cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
    cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;

白马王子;可以用对如下函数的调用来替换:

carObject.Category = userInput( "category", categoryOptions );

显然它返回一个string(也就是一个std::string)。

options参数最好改成vector<string>


然后将其他类似的块替换为对该函数的相同调用。


让这个函数成为Car的成员函数好吗?

例如,考虑如何在GUI程序(图形用户界面)中使用Car