conditional statement in while loop

前端 未结 2 1976
情歌与酒
情歌与酒 2021-01-25 17:48

I must have missed something. I\'m doing an exercise to learn c++ and it asks that if a user inputs either c,p,t or g character then carry on, otherwise re-request prompt, so I

相关标签:
2条回答
  • 2021-01-25 18:04

    My understanding is that the "OR" statement should work as one of the tests is correct.

    Well, you could use ||, but the expression would have to be:

    while(!(ch == 'c' || ch == 'p' || ch == 't' || ch == 'g'));
    

    By applying the De Morgan's law, the above simplifies to:

    while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');
    
    0 讨论(0)
  • 2021-01-25 18:12

    why is that? My understanding is that the "OR" statement should work as one of the tests is correct.

    Exactly. There is always one of the tests that passes. A character will either be not 'c', or not 'p'. It can't be both 'c' and 'p'. So the condition is always true, leading to an infinite loop.

    The alternative condition with the conjunctions works because it is false as soon as ch is equal to one of the alternatives: one of the inequalities is false, and thus the whole condition is false.

    0 讨论(0)
提交回复
热议问题