2015-10-02 298 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 –

相關問題