Hello there, I'm trying to write an interactive story game that outputs a paragraph to the console window, then asks you to make a choice what the character should do next. It works fine but I wanted to put a function in to make sure that the user inputs 1, 2, or 3. Because currently it goes a bit wrong if you don't. The current function I'm using goes as follows:
But this goes really wrong if you don't enter the right choices. Is there a convenient function that just takes in specific key presses or something instead? Thanks for any help you can offer.
P.S. I'm pretty much an absolute beginner so please use small words.
You could probably build this function into your display menu function, as I'm sure you will be using both at the same time.
Meanwhile, how about doing it by value instead of by each number?
1 2 3
while (choice <=0 || >=4)
{cout << "Please enter a valid choice." ;
cin >> choice;}
The only way to escape that loop is with a 1,2, or 3 and the only way to enter it is with a valid value. If you decide to use more than 3 choices, it is easy to modify. You can even have the number of choices modified while running by using variables.
Thanks for you help bsonline but unfortunately that code doesn't build. When I altered it a bit to:
while ((choice < 1) || (choice > 3))
and added a return value of "choice", it came up with the same problem as before. If you type in a load of jibberish, it outputs please enter a valid choice indefinately. This is unfortunately what I was getting with my code.
Thanks again for your help though.
Cheers for all your help everyone, I found the solution in the end. Copied some code from http://www.cplusplus.com/forum/articles/6046/
in the end. Modified it a bit. Now all is well.