2017-02-28 9 views
0

読んでいない場合は、if文は、変数選択肢を無視しているようだと選択肢が「L」または「L」であるかのようにプログラムが継続的に実行されます。は、ステートメントがchar変数を適切に

if文が無視される理由は何ですか?私はプログラムの実際のコードを省略しました。

#include <iostream> 
using namespace std; 

void starLeftTriangle(int n); 
void starRightTriangle(int n); 


int main() { 
int star; 
char choice; 
cout << "Input the number of stars you want to draw: \n"; 
cin >> star; 
cout << "Would you like to draw a left triangle, right triangle, or quit?  \n"; 
cin >> choice; 

cout << "The choice value is " << choice << endl; 

system("pause"); 

while (choice != 'q' || 'Q'){ 
    if (choice == 'l' || 'L'){ 
     starLeftTriangle(star); 
    } 
    else if (choice == 'r' || 'R') { 
     starRightTriangle(star); 
    } 
} 
if (choice == 'q' || 'Q') { 
    cout << "Quitting Program."; 

} 
else{ 
//throw error 
} 
return 0; 

}

+1

'選択肢を!= 'q' || 「Q」はあなたが思っていることをしません。それは ''選択 ''が '' q ''でないか、 '' Q''が真であり、後者が常に真であることを意味します。 – Biffen

答えて

2

はあなたのwhileif条件に期の平等/不平等を表現する必要があります。

while (choice != 'q' && choice != 'Q') { 
    if (choice == 'l' || choice == 'L') { 
     starLeftTriangle(star); 
    } 
    else if (choice == 'r' || choice == 'R') { 
     starRightTriangle(star); 
    } 
} 
if (choice == 'q' || choice == 'Q') { 
    cout << "Quitting Program."; 
} 
else { 
    // throw error 
} 

私は、現在起こっていると思うことになるいくつかの値についてchoice以下のifの状態が常に発生しています。

実際に 'l'が、これは本当だろうことがあれば
if (choice == 'l' || 'L') { 
    starLeftTriangle(star); 
} 

その理由は、そうでない場合、あなたの他の条件もtrueに評価されます'L'、です。これを避けるには、どこでも等しく使用してください。

+0

@Biffen編集ありがとう:-) –

+0

あなたは男です。ありがとうございました。 – Jonathan

+0

彼が最初の条件で望んでいるのは '(choice!= 'q' && choice!= 'Q')'だと思います。 '(choice!= 'q' || choice!= 'Q') 'という条件は常に真で無限ループになります。 – user1488118

1

次のようにあなたの条件に解釈されている:choice == 'q' OR 'Q'を - それは常にcompraison
内の任意の文字のためtrueを返しますので、Qの整数コードは、0以上で、このいずれかを試してみてください:

bool loop = true; 
while (loop) { 
    switch ((int) choice) { 
    case (int) 'l': 
    case (int) 'L': 
     starLeftTriangle(star); 
     break; 
    case (int) 'r': 
    case (int) 'R': 
     starRightTriangle(star); 
     break; 
    case (int) 'q': 
    case (int) 'Q': 
     loop=false; 
     break; 
    } 
} 
関連する問題