为什么我的同时循环不会继续循环?

Why won't my do-while loop continue looping?

本文关键字:循环 继续 为什么 我的      更新时间:2023-10-16

我正在创建一个带有错误检查的菜单,这就是我想出来的,但是我似乎不能让它工作。

#include <iostream>
using namespace std;
int main() 
{
char option; // user's entered option will be saved in this variable
int error1 = 0;
 //Displaying Options for the menu
cout << "There are three packages available." << endl;
cout << "Monthly Price - Price per MB for overages (excluding C)" << endl;
cout << "A) $15 - $.06 for each MB after 200 MB." << endl;
cout << "B) $25 - $.02 for each MB after 2,000 MB ( approx. 2 GB)." << endl;
cout << "C) $50 - Unlimited data." << endl;
do //do-while loop starts here
{ 
 //Prompting user to enter an option according to menu
 cout << "Please enter which plan you currently have : ";
 cin >> option;  // taking option value as input and saving in variable "option"
 if(option == 'A' || option == 'a') // Checking if user selected option 1
 {
    cout << "You chose a" << endl;
    error1 = 1;
 }
 else if(option == 'B' || option == 'b') // Checking if user selected option 2
 {
    cout << "You chose b" << endl;
    error1 = 1;
 }
 else if(option == 'C' || option == 'c') // Checking if user selected option 3
 {
    cout << "You chose c" << endl;
    error1 = 1;
 }
 else //if user has entered invalid choice 
 {
   //Displaying error message
   error1 = 0;
   cout << "Invalid Option entered";
 }
 }
while(error1 = 0);  //condition of do-while loop
return 0;
}

当输入错误的值时,输出将是Invalid Option entered;但是,它不会循环回到开头并提示用户再次输入。

它为什么这样做?

变化

while(error1 = 0);  //condition of do-while loop

while(error1 == 0);  //condition of do-while loop

在第一个选项中,您只是将0分配给error1,然后error1被测试为布尔值,这意味着0为FALSE,非0为TRUE。因此,一旦while中的条件被评估为FALSE,循环结束。

您将0分配给while中的error1,这始终为假,因此循环不会重复。修改while(error1=0);while(error1==0);

就像补充一样:考虑将表达式反转如下:

while (0 = error1);

通过这种方式,如果您忘记了额外的=或将赋值与相等操作符

混淆,编译器将阻止您。