2016-02-14 133 views
0

我一直有一个问题,得到的if语句正常工作的代码。C++ while语句,嵌套if else

我有我需要它的一切,只是我们应该有多个条目输入,它只是自动使用响应和else语句不起作用。

int main() 
{ 
    string dep = "Deposit";   
    string with = "Withdrawl";  
    string bal = "Balance";   

    char choice;     

    cout << "PLease enter options A, B, C, or Q to quit.\n"; 
    cin >> choice; 

    switch (choice) //to make them all the same, same as using toUpper 
    { 
     case 'a': 

     case 'A': 
      cout << ""; 
      break; 

     case 'b': 

     case 'B': 
      cout << ""; 
      break; 

     case 'q': 

     case 'Q': 
      cout << ""; 
      break; 
    } 

    int count = 1; 

    while (count <= 4) 
    { 
     if (choice == 'a' || 'A') 
      cout << dep << endl; 
     else if (choice == 'b' || 'B') 
       cout << with << endl;    
      else if(choice == 'c' || 'C')   
        cout << bal << endl;    
       else 
        (choice !='a' && choice !='b' && choice !='c'); 

     cout << "that is invalid, PLease enter options A, B, C, or Q to quit.\n"; 

     ++count ; 
    } 

    system ("PAUSE"); 

    return 0; 
} 
+2

'if(choice =='a'||'A')'不符合您的想法。您需要'if(choice =='a'|| choice =='A')'等。注意:您也可以将所有输入转换为大写或小写以减少测试。 –

+3

另外,'else(choice!='a'&& choice!='b'&& choice!='c');'缺少'if',并且不应该有';'打算在那里完成。 – jogojapan

+2

最后,您不会在循环中读取新的用户输入。您只需循环四次原始输入字符即可。 – jogojapan

回答

1

您需要解决这样的条件语句:

if (choice == 'a' || choice == 'A') 

你总是会导致第一个条件得到满足,因为“A”等于什么十进制数65

+0

我建议您查看您的推理和运营商优先级。如果我使用另一个校验序列,其中'A'不是0x41,你的理由是否仍然成立? –

+0

我实际上试图删除我的答案,但堆栈交换应用程序不会让我,当我尝试在浏览器中访问该网站时,应用程序崩溃... –

+1

此外,要回应您的评论, ==''在'||'之前,并且'A'将总是等于大于0的某个整数,所以我看不出我的推理在这里有问题。 –

-1

if(choice == 'a'||'A'),电脑先运行'a'||'A',然后返回1(在bool中),然后运行 choice == 1,根据你的代码,没有choice == 1,所以if中的代码不会运行。

+3

实际上,'=='比'||'具有更高的优先级。 – jogojapan