在类 c++ 中执行 while 循环

Do while loop in class c++

本文关键字:while 循环 执行 c++ 在类      更新时间:2023-10-16

我遇到了一个问题,更多的是个人困惑,我的部分代码。你看到的重点是,在询问用户给出的n名称数量权重的问题之后,它应该问"添加更多?"如果回答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中的类中,有什么方法可以使其以这种方式工作吗?

除了代码中的一些语法(不正确的括号(错误外,我还可以看到一些逻辑错误。这可能是您寻找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作为输入。

希望这能解决您的问题!