菜单中的C 循环

C++ Loop in menu

本文关键字:循环 菜单      更新时间:2023-10-16

在我的代码中,即使我输入'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;
}

您要在测试中使用和(&&)操作员,而不是OR(||)操作员。否则,selection != 'Q'selection != 'q'之一将永远是正确的,您的循环永远不会退出。

正如指出的那样,||无法满足您的要求。您需要使用&&操作员。

如果按q,这就是情况。

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

如果按Q,那就是情况。

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

循环应该是这样的。

while((selection != 'Q' && selection != 'q'));

尝试一下:

} while((selection != 'Q' && selection != 'q'));

使用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 continuen";
  cin.ignore();
  cin.get();
   return 0;
}