C++ do-while循环不断重复

C++ do-while循环不断重复,c++,C++,我有一个代码片段(我们在银行系统上分配了一个学校项目,这是第一个登录屏幕,请注意,这个代码片段在main()函数中),类似这样: int choice; do { clrscr(); // for clear screen cout << "1. Help!" << endl; cout << "2. About Us..." << endl; cout << "3. Log In" <<

我有一个代码片段(我们在银行系统上分配了一个学校项目,这是第一个登录屏幕,请注意,这个代码片段在main()函数中),类似这样:

int choice;

do
{
    clrscr(); // for clear screen
    cout << "1. Help!" << endl;
    cout << "2. About Us..." << endl;
    cout << "3. Log In" << endl;
    cout << "4. Sign Up" << endl;
    cout << "Option: ";
    cin >> choice;
}while((choice != 1) || (choice != 2) || (choice != 3) || (choice != 4));
int选择;
做
{
CLRSC();//用于清除屏幕
简短回答:
当
choice
与1不同,或与2、3或4不同时,重复此操作。如果
choice
的值正确,则会因为其他3个条件而循环

while((choice != 1) || (choice != 2) || (choice != 3) || (choice != 4));
您可能是指
&&

while(choice != 1 && choice != 2 && choice != 3 && choice != 4);
或:

如果您还记得
!(a | | b)=(!a&&!b)
,您还可以编写:

while (choice != 1 && choice != 2 && choice != 3 && choice != 4);
这也是有意义的:循环whilechoice不同于1和2以及3和4

您还可以确定正确的含义:
choice>=1&&choice=1&&choice 4);

您已经告诉它,如果选项不是1或不是2,则继续运行。您可能是指不是1或不是2,等等。

循环条件将始终为真;
选项
不能同时具有所有这些值


大概,您打算使用
&&
,这样当
选项
具有这些值中的任何一个时,循环就会终止。

如果有人输入类似“do number one”的内容,您将遇到cin问题,因此我建议您将代码更改为以下内容

# include <iostream>
#include <stdlib.h>
# include <string>
# include <sstream>

using namespace std;

int main ()
{
string choice="";

int num = 0;

 while (true) {

   system("cls"); // for clear screen
   cout << "1. Help!" << endl;
   cout << "2. About Us..." << endl;
   cout << "3. Log In" << endl;
   cout << "4. Sign Up" << endl;
   cout << "Option: ";
   getline(cin, choice);

   stringstream Stream(choice);
   if (Stream >> num)
     break;
   cout << "Invalid number, please try again" << endl;
 }

}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串选择=”;
int num=0;
while(true){
系统(“cls”);//用于清除屏幕

cout
while((choice!=1)&&&(choice!=2)&&(choice!=3)&&&(choice!=4))
只要条件为true,“OR”运算符|如果其任一操作数为true,则返回true。也就是说,如果choice!=1 | choice!=2,则始终为true。(如果choice==1,它是!=2,那么第二个子表达式是真的。如果choice==2,那么它是!=1,那么第一个子表达式是真的。无论哪种方式,它都是真的。您要确保它不等于任何值,而不是它至少与其中一个值不同。
while (choice != 1 && choice != 2 && choice != 3 && choice != 4);
while (!(choice >= 1 && choice <= 4));
while (choice < 1 || choice > 4);
# include <iostream>
#include <stdlib.h>
# include <string>
# include <sstream>

using namespace std;

int main ()
{
string choice="";

int num = 0;

 while (true) {

   system("cls"); // for clear screen
   cout << "1. Help!" << endl;
   cout << "2. About Us..." << endl;
   cout << "3. Log In" << endl;
   cout << "4. Sign Up" << endl;
   cout << "Option: ";
   getline(cin, choice);

   stringstream Stream(choice);
   if (Stream >> num)
     break;
   cout << "Invalid number, please try again" << endl;
 }

}