-3

Hello I am doing a very simple while loop in C++ and I can not figure out why I am stuck in it even when the proper input is give.

string itemType = "";
        while(!(itemType == "b") || !(itemType == "m") || !(itemType == "d") || !(itemType == "t") || !(itemType == "c")){
            cout<<"Enter the item type-b,m,d,t,c:"<<endl;
            cin>>itemType;
            cout<<itemType<<endl;
        }
        cout<<itemType;

if someone can point out what I am over looking I'd very much appreciate it. It is suppossed to exit when b,m,d,t or c is entered.

4 Answers4

1

Your problem is in your logic. If you look at your conditions for your while loop, the loop will repeat if the item type is not "b" or not "m" or not "d" etc. That means if your item type is "b", it is obviously not "m", so it will repeat. You want to use && instead of ||.

Tophandour
  • 297
  • 5
  • 15
1

As other answers and comments wrote correctly your logic is wrong. Using find() would simplify your task:

std::string validCharacters( "bmdtc" );
while ( std::string::npos == validCharacters.find( itemType  ) )
{
    ...
}

This solution is more general and easier to read. See also documentation of std::string::find

Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
0

The boolean expression to exit the loop is flawed. The way it is, in order to exit the loop the itemType would have to be all those letters at the same time. Try to instead || the letters first, and then negate it:

while(!(itemType == "b" || itemType == "m" || itemType == "d" || itemType == "t" || itemType == "c")

Bettorun
  • 227
  • 1
  • 3
  • 8
0

try this

string itemType = "";

    while(!(itemType == "b" || itemType == "m" || itemType == "d" || itemType == "t" || itemType == "c")){

        cout<<"Enter the item type-b,m,d,t,c:"<<endl;

        cin>>itemType;

        cout<<itemType<<endl;

    }

    cout<<itemType;

you condition is always true