-3

I'm trying to have the user be able to control when they want to exit the while loop, and also i was wondering on how to exit the program when done

    cout<<"Play again? (Y/N)"<<endl;
char userInput;
cin>>userInput;
if (userInput='y'|'Y')
{
   cin.clear();
   cin.ignore();
   input();
   userInput=0;
}


else

{
    exit(0);
}
return 0;
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • See https://stackoverflow.com/q/15052737/1270789 and https://stackoverflow.com/q/151850/1270789 (Also, there's no `while` loop) – Ken Y-N Jan 19 '18 at 02:57
  • 1
    `userInput='y'|'Y'`: That's not how conditional expressions work. – Christian Dean Jan 19 '18 at 03:01
  • See also [which-are-the-most-common-pitfalls-with-conditional-if-statements-in-c](https://stackoverflow.com/questions/47959876/which-are-the-most-common-pitfalls-with-conditional-if-statements-in-c) – Jarod42 Jan 19 '18 at 09:21

1 Answers1

2

The expression userInput='y'|'Y' suffers from three fundamental problems and a compounding problem.

  1. 'y'|'Y' is not a logical OR operation. It is a bitwise OR operation.
  2. It does not compare the value of userInput against 'y' or 'Y'.
  3. It assigns the value of the subexpression 'y'|'Y', which evaluates to the integral value 121 in a system that uses ASCII encoding, to userInput.
  4. As a consequence, the conditional of the if statement always evaluates to true.

What you need is:

if ( userInput == 'y' || userInput == 'Y' )
R Sahu
  • 204,454
  • 14
  • 159
  • 270