If statements in a do while loop with a yes or no ending

  • A+

I am new to coding and I'm trying to do a long do while loop with nested if statements but I'm having issues with getting my loop to actually loop.

Instead of getting help directly on my project, which has a very long code, I made a simple kind of like it version. It also does not loop. It will get to the end and ask the user if they want to try again but when "y" is entered it ignores the if statements.

#include <iostream> #include <string> using namespace std;  int main() {     string sodaChoice;     char answer = 'n';      do     {         cout << "Please choose your favorite soda from the following: Rootbeer, Diet Coke, Coke, Sprite" << "/n";         getline(cin, sodaChoice);          if (sodaChoice == "Rootbeer")         {             cout << "Me too!" << "/n";         }         else if (sodaChoice == "Diet")         {             cout << "Not me :(" << "/n";         }         else if (sodaChoice == "Coke")         {             cout << "It's alright" << "/n";         }         else if (sodaChoice == "Sprite")         {             cout << "only if I'm sick" << "/n";          }         else         {             cout << "That was not on the list";         }         cout << "would you like to try again?";         cin >> answer;        } while (answer == 'y'|| answer == 'Y');         return 0; } 

I thought maybe I needed a do loop in the do loop around the if statements but then I didn't know how to go about it. Any help would be appreciated. I have spent many, many hours trying to figure it out.

I tried to ask my teacher, but my college teaches from some generic curriculum that their dean wrote based on her book. He is not very enthusiastic about helping or teaching.



cin >> answer; 

you read exactly one character. The problem is that you entered at least two characters when writing the answer. The actual 'y' or 'n' plus the Enter key, which is added as a newline in the input buffer.

This newline is then read by the next getline call as an empty line.

There are a few solutions to this problem, for example using ignore after reading into answer. Or if you want only one-word inputs then you could use formatted input using >> for sodaChoice too, since it will by default skip leading white-space (like newlines).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: