While Loop entering Infinite loop

I developed a while loop that allows the user to enter 'y' or 'n' if they'd like to deposit more, however, if the user enters an invalid character, the while loop should take them to the beginning where they have to attempt to enter their choice again, however, it seems to enter an infinite loop. This previously worked (or so I thought).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cout << "You've Chosen to check your Account Balance:" << endl;
            printAllStats();
            char yn;
            cout<<endl;
            cout<< "Would you like to deposit more US$ onto your account? (Y/N)"<<endl;
            cin>>yn;
                while (yn != 'y' || 'n')
                    {

                        if (yn == 'y')
                        {
                           deposit(&amount, &deposits);
                           cout<<endl;
                           break;
                        }
                        if (yn == 'n')
                        {
                            cout <<endl;
                            break;
                        }
                        cout<<"Invalid response...Would you like to deposit more US$ onto your account? (Y/N)"<<endl;
                    }
                    break;
Last edited on
while (yn != 'y' || 'n')

The right hand side of your || is always true. Maybe you meant while (yn != 'y' || yn!= 'n'), except that also will run forever. I thikn you've just massively misunderstood how boolean logic works.

What are you trying to do? Are you trying to make the user keep entering letters until they enter y or n?


closed account (E0p9LyTq)
You want to repeat when you don't get the correct input (y or n). A do/while loop is a better solution than a while loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char yn = '\0';

do
{
   cout << "Would you like to deposit more US$ onto your account? (Y/N)" << endl;
   cin >> yn;

   if (yn == 'y')
   {
      deposit(&amount, &deposits);
      cout << endl;
      break;
   }
   if (yn == 'n')
   {
      cout << endl;
      break;
   }
   cout << "Invalid response...Would you like to deposit more US$ onto your account? (Y/N)" << endl;
} while (yn != 'y' || yn != 'n');
(yn != 'y' && yn != 'n');
thank you @FurryGuy
Topic archived. No new replies allowed.