退出简单的while循环时遇到问题

时间:2018-10-29 04:34:48

标签: c++

因此,我正在尝试编写一个从用户那里获取价值并应该在用户键入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;

}

2 个答案:

答案 0 :(得分:2)

您正在使用or语句&&。当然,该字符串将不等于一个,也不等于另一个。

您需要使用和cin。如果不是'q'并且不是'Q',则循环。

您还应该检查if是否有效。您的整个while(cin && nameOfpart != "q" && nameOfpart != "Q") { 语句可能是:

>>> from collections import defaultdict
>>> 
>>> result = defaultdict(list)
>>> for k, v in rating.items():
...:    result[v].append(k)
...:    
>>> result
>>> 
defaultdict(list,
            {'excellent': ['bob', 'baxter', 'belle'],
             'no pass': ['ben'],
             'passing': ['barnum', 'bernice', 'bill', 'bernie'],
             'satisfactory': ['beatrice']})

答案 1 :(得分:2)

如果输入“ q”,则“ q”!=“ Q”为真,然后继续,反之亦然。 您应该改用

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