【问题标题】:Do while loop in class c++在 C++ 类中执行 while 循环
【发布时间】:2020-09-19 01:40:51
【问题描述】:

我遇到了一个问题,更多的是个人混淆,我的一部分代码。你看重点是在询问用户给出的关于名称数量权重的问题后,它应该问“添加更多?”如果回答 Y 或 y,它应该再次询问您想要多少产品或只添加 1 个。

class Class
{
public:
    char ask;
    vector <string> names;
    vector <int> amounts;
    vector <float> weights;
    string name;
    int amount, n;
    float weight;
    void market()
    {
        cout << "Give the number of products you want to get at Market : " << endl;
        cin >> n;
    }

void get()
{
    for (int i = 0; i < n; i++)
            {
                do
                {
                cout << "Give product name,amount and weight : " << endl;
                cin >> name >> amount >> weight;
                cout << endl;
                names.push_back(name);
                amounts.push_back(amount);
                weights.push_back(weight);
                }
                cout << "Add more? (Y/n): "; // add more? Go on if yes...
                cin >> ask;

            }while (ask == 'Y' || ask == 'y');

        }
};

这一切都在我后来放在main中的一个类中,有什么办法让它这样工作吗?

【问题讨论】:

  • 尝试删除cout上方的}。看起来你的花括号没有对齐。
  • ... 这就是为什么你应该正确缩进你的代码。然后,这样的问题就更容易看到了。

标签: c++ function loops class while-loop


【解决方案1】:

除了代码中的一些语法(不正确的括号)错误外,我还可以看到一些逻辑错误。这可能是您寻找 get() 函数的方式:

void get()
{
    for (int i = 0; i < n; i++){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
    }
    cout << "Add more? (Y/n): "; // add more? Go on if yes...
    cin >> ask;
    while (ask == 'Y' || ask == 'y'){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
        cout << "Add more? (Y/n): "; // add more? Go on if yes...
        cin >> ask;
    }
}

上面的代码将首先从用户那里获取n个输入,然后询问用户是否要输入更多数量的项目。 while() 循环将一直运行,直到用户输入 Yy 作为输入。

希望这能解决您的问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多