3

在我的代码中存在一个问题,即使我输入“Q”或“q”,程序也会不断循环菜单。这里有什么问题?这是代码:

{
    char selection;
    do {
        cout << "Add a county election file         A" << endl;
        cout << "Show election totals on screen     P" << endl;
        cout << "Search for county results          S" << endl;
        cout << "Exit the program                   Q" << endl;
        cout << "Please enter your choice: ";
        cin >> selection;
    } while ((selection != 'Q' || selection != 'q'));
    return 0;
}
4

4 回答 4

11

您想&&在测试中使用 And ( ) 运算符,而不是 Or ( ||) 运算符。否则,selection != 'Q'and之一selection != 'q'将始终为真,并且您的循环将永远不会退出。

于 2012-10-28T15:37:23.313 回答
3

正如所指出的,||不满足您的要求。您需要使用&&运算符。

如果你按q,那么情况就是这样。

(selection != 'Q' || selection != 'q')
|---------------|    |--------------|
    true                  false

如果你按Q,那么情况就是这样。

(selection != 'Q' || selection != 'q')
|---------------|    |--------------|
    false                  true

循环应该是这样的。

while((selection != 'Q' && selection != 'q'));
于 2012-10-28T15:38:35.407 回答
2

试试这个:

} while((selection != 'Q' && selection != 'q'));
于 2012-10-28T15:40:15.973 回答
0

使用toupper().

如果你这样做, while ( toupper(selection) != 'Q' )你将不需要检查大小写。

#include <iostream>
#include <stdio.h>
using namespace std;

int main(void)
{



    char selection;
    do {
        cout << "The Menu" << endl;
        cout << "____________________________________" << endl;
        cout << "Add a county election file         A" << endl;
        cout << "Show election totals on screen     P" << endl;
        cout << "Search for county results          S" << endl;
        cout << "Exit the program                   Q" << endl;
        cout << "____________________________________" << endl;
        cout << "Please enter your choice: ";
        cin >> selection;
    } while ( toupper(selection) != 'Q'  );



  cout<<" \nPress any key to continue\n";
  cin.ignore();
  cin.get();

   return 0;
}
于 2012-10-28T16:06:38.043 回答