2015-10-02 175 views
2

我正在创建一个错误检查菜单,这是我想出来的,但我似乎无法得到它的工作。为什么我的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; 
} 

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

它为什么这样做?

+3

改变while(error1 = 0);进入while(error1 == 0); –

+1

这只是一个错字,你分配而不是检查是否相等。 – shuttle87

+3

调高编译器的警告级别。 –

回答

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

+0

完全错过了这一点,感谢你是另一双眼睛。 –

+0

@AugieLuebbers欢迎您。这是一个非常普遍的错误。 –

1

您正在将0指定为while内的error1,因为它始终为假,所以循环不会重复。更改while(error1=0);while(error1==0);

+0

谢谢,我没有听到! –

1

正如补充:考虑这样反转的表达:

while (0 = error1); 

这样编译器会阻止你,如果你忘记了额外=或与等运营商混淆分配

+0

没有想到这一点,但听起来像一个好主意。我将铭记未来。谢谢@lrleon –

相关问题