为什么我的do-while循环会继续循环?

时间:2015-10-02 22:25:41

标签: c++ do-while

我正在创建一个带有错误检查的菜单,这就是我提出来的,但我似乎无法让它发挥作用。

#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;
}

输入错误值时,输出将输入无效选项;但是,它不会循环回到开头并再次提示用户输入。

为什么要这样做?

3 个答案:

答案 0 :(得分:4)

更改

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,循环结束。

答案 1 :(得分:1)

您要在 noDuplicatedDF.write.mode(SaveMode.Append).parquet("lookup") 内为0分配error1,这始终为假,因此循环不会重复。将while更改为while(error1=0);

答案 2 :(得分:1)

正如补充:考虑反过来表达式:

while (0 = error1);

通过这种方式,如果您忘记了额外的=或者使用相等的运算符混淆了赋值,编译器将阻止您