iteration within an if statement with a string variable

Hello,

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";
}

else {
std::cout << "Wrong, try again: ";
std::cin >> bestseries;
}

}

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.
Last edited on
@Mjn4,
Please learn to use code tags, they make reading and commenting on source code MUCH easier.

How to use code tags: http://www.cplusplus.com/articles/jEywvCM9/

There are other tags available.

How to use tags: http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either
I will follow your advice, thank you very much!
Do you mean this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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";
		else if (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.
One thing to note about string matching, the case of the letters matters. "The" is not the same as "the". Or "tHe", etc.
Topic archived. No new replies allowed.