Issues with Do while

Basically I just want this code to repeat over if someone enters anything but y,Y, n,N using a Do while loop. But after an answer is entered it infinity loops the corresponding text and never stops. I'm guessing it has to do with

} while ( answer != 'n', 'N', 'y','Y'); but I'm not sure about how to go along fixing it. Any tips would be appreciated.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>
using namespace std;


int main ()
{
cout << "do you like cheese cake? " << endl;

char answer ;
cin >> answer;

do {
if (answer == 'Y' || answer == 'y')
cout << "Good for you" << endl;

else if ( answer == 'N' || answer == 'n' )
cout <<"okay thats fine to" << endl;

else 
cout << (" you cant read man" ) << endl;

} while ( answer != 'n', 'N', 'y','Y');

return 0;
}
         the code you need help with here.
This line has correct syntax (the compiler will accept it), but it doesn't do anything sensible:
while ( answer != 'n', 'N', 'y','Y');

Your previous code was correct, where you had
if (answer == 'Y' || answer == 'y')
that is, each value must be individually tested.

The only difference in the while condition is that you are using != rather than ==.
Because of that, you need to use && rather than ||
 
while (answer != 'n'  &&   answer != 'N'  &&  answer !=  'y'  &&  answer != 'Y');

Now that fixes the problem when entering y,Y,n, N. But anything else still makes the last else repeat. Shouldn't it just reset and restart the loop?
Your problem is that the user can only enter an answer once. When the answer isn't Y,y,N or n, your program loops and checks the condition again, but the answer hasn't been changed at all resulting in an endless loop.

You have two options:

1. Write your code in a way that lets the user re-enter an answer in case it wasn't yes or no.
2. Add break; in your last else to force-exit the loop, but that ruins the whole purpose a using a do while loop.
Well, once the loop has been entered, there is no way to change the value of answer. Thus if it isn't y or n, the loop will repeat forever. To fix it, move the line cin >> answer; so that it is after the start of the loop
1
2
3
    do {
        cin >> answer;
        // etc. 

You may also want to move the question inside the loop too, or change the "you can't read" message so the user will know they are expected to try again with a different answer.
Topic archived. No new replies allowed.