退出简单while循环时出现问题

Having problems from exiting a simple while loop

本文关键字:问题 循环 简单 while 退出      更新时间:2023-10-16

因此,我正试图编写一个程序,该程序从用户那里获取值,并且应该在用户键入q后停止,但由于某些原因,该程序无法运行,即使在我使用q或q进行测试后,该程序也不会停止运行。

vector <string> names;
vector <int> ticPurch; 
int numOfRaff; 
string nameOfpart; 
cout << "Enter the name of the participant, enter q to quit " << endl; 
cin >> nameOfpart; 
while(nameOfpart != "q" || nameOfpart != "Q"){
names.push_back(nameOfpart);
cout << "Please enter the number of tickets the participant bought " << endl; //Getting input and storing them in vector
cin >> numOfRaff; 
ticPurch.push_back(numOfRaff);
cout << endl; 
cout << "Enter the name of the participant, enter q to quit " << endl; 
cin >> nameOfpart;
}

您使用的是或语句||。当然,字符串将不等于一个或不等于另一个。

您需要使用和&&。如果它不是"q"AND它不是"q",则循环。

您还应该检查cin是否有效。您的整个if语句可能是:

while(cin && nameOfpart != "q" && nameOfpart != "Q") {

如果输入"q",则为"q"!="Q"是真的,然后它继续,反之亦然。你应该使用

while(nameOfpart != "q" && nameOfpart != "Q")