0

I'm new to C so I'm sorry if it's a really silly mistake, but I can't seem to figure out why my code isn't working. All it should do is take in input from the user until the user inputs either "y" or "n". However, the loop doesn't break when I input "y" or "n" (or anything else!).

do{
    printf("Would you like a daily newspaper (y/n): "
    scanf("%c",&news);       //get newspaper preference
    news= tolower(news);
    fflush(stdin);
}while((news !=  'y') || (news != 'n'));

I tried running the bits of code individually, and it seems to be working then. Not sure what I've done wrong.

aquasense
  • 9
  • 2
  • 4
    `fflush(stdin)` is Undefined behavior – user2736738 Nov 18 '17 at 17:42
  • 6
    At least one of the two conditions in the OR clause will always be true. You probably want an AND here. – M Oehm Nov 18 '17 at 17:42
  • 2
    `scanf(" %c",&news); ` otherwise `\n` will be consumed by the next `scanf()` call – user2736738 Nov 18 '17 at 17:44
  • This `((news != 'y') || (news != 'n'))` is the same as `!((news == 'y') && (news == 'n'));` (for details see [De Morgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws)). – alk Nov 18 '17 at 17:45
  • thank you all the code is now working! – aquasense Nov 18 '17 at 17:49
  • `(news != 'y') || (news != 'n')` is always true. They cannot be both false on the same time (that could happen only when `news` is simultaneously `'y'` and `'n'`, which is impossible). The condition you need is `(news != 'y') && (news != 'n')`. – axiac Nov 18 '17 at 17:50
  • If you still have `fflush(stdin);` and your program is running, you are / might be in trouble. – babon Nov 18 '17 at 17:51
  • @babon what do you mean? – aquasense Nov 18 '17 at 18:03
  • Read this; https://stackoverflow.com/questions/9122550/fflushstdin-function-does-not-work and https://en.wikipedia.org/wiki/Undefined_behavior – babon Nov 18 '17 at 18:09

0 Answers0