unlike while statements, if statements allow several answers to have a character output stream, but without iteration.
Here, I have a string variable and I would like to make sure that there are several correct answers, each with a character output stream, plus an iteration in case of a wrong answer. Here is an example program:
#include <iostream>
int main() {
std::string bestseries;
std::cout << "What is the best series? ";
std::cin >> bestseries;
if (bestseries == "stranger things") {
std::cout << "nostalgic and funny!\n";
}
else if (bestseries == "the queen's gambit") {
std::cout << "unique and memorable!\n";
}
This is where, if there is an answer other than "the queen's gambit" or "stranger things", the user should be able to enter another answer until they have one of the two,
however I am stuck at this stage.
Is there a better alternative than if statements? Or is it possible to have an iteration or a loop within an if statement?
Thanks in advance for your answers!
Put the code that you want to repeat inside a loop.
Then think how you can make it stop/continue correctly.
There are many different ways you could do this.
You could use use break to end the loop.
You could put a break at the end and use continue if you want to skip the break.
You could use boolean flag that decides if you should repeat the code and that you change inside the loop to decide whether you should continue or not.
Try different ways and see what you like best.
You'll learn from it. It's not always easy to know what is the best way to do things before you've tried.
#include <iostream>
#include <string>
int main() {
std::string bestseries;
bool bad {};
do {
bad = false;
std::cout << "What is the best series? ";
std::getline(std::cin, bestseries);
if (bestseries == "stranger things")
std::cout << "nostalgic and funny!\n";
elseif (bestseries == "the queen's gambit")
std::cout << "unique and memorable!\n";
else {
std::cout << "Wrong, try again\n";
bad = true;
}
} while (bad);
}
Note that >> will only extract string input up to white space (space, tab. \n). Use getline() to obtain the whole line.