-2
while(ans == 'Y' || 'y')
{
    cout<<"--MENU--"<<endl;
    cout<<"1.Create a file"<<endl;
    cout<<"2.Display that file"<<endl;
    cout<<"3.Exit"<<endl;
    cout<<"Enter your choice-";
    cin>>ch;

    switch(ch)
    {
        case 1:
            create();       //create and display functions are written above this, which are not required 
            break;
        case 2:
            display();
            break;
        case 3:
            exit(0);
    }

    cout<<"Do you want the menu again?(Y or y for Yes and anything else for a No)";
    cin>>ans;
}

My expectation is:-

When the input is other than Y or y in ans in the last line, the control of the program should exit the loop and execute the next line...

However it executes while loop again. Why?

Suppose if the input is n in the last line, then the compiler should check whether ans contains the character Y or y and should exit the loop.

Dark Matter
  • 300
  • 2
  • 15
  • 1
    Does this answer your question? [If always returns true](https://stackoverflow.com/questions/32035762/if-always-returns-true) – Tom Dec 27 '19 at 05:30

1 Answers1

3

The condition inside the while ans=='Y'||'y' always evaluates to true.

It should actuay be: ans == 'Y' || ans == 'y'

The way it was written, it only evaluates the equality comparison for ans=='Y' and then it does a logical or with 'y' which is interpreted as true (any non 0 value in C is considered true) so the whole condition is always evaluated true, regardless of the first part. I hope this makes sense.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151