Using rand and while loops for Selection Menus?

Hello, I am in need of assistance on how to correctly output a selection menu using the rand function and while loops. I aim to have the line of code randomly output different statements from the first two selections, and for the program to continuously loop the number 3 is typed into the console.


Here is a rough draft for my line of code.

#include<iostream>
#include<string>
using namespace std;

int main(){

int number;

cout<<"**************"<<endl;
cout<<"Random Selection Generator"<<endl;
cout<<"**************"<<endl;

cout<<"1. Fortune Cookie saying."<<endl;
cout<<"2. Bible Verse."<<endl;
cout<<"3. Quit"<<endl;
cin>>number;

//Random Outputs?
while (number == 1){
cout<<"Good Luck is coming your way!\n"<<endl;
break;
}
while (number == 1){
cout<<"Bad Luck is coming your way!\n"<<endl;
break;
}

//Repeat Until Quit?
while (number == 1 || number == 2)
{
cout<<"**************"<<endl;
cout<<"Random Generator"<<endl;
cout<<"**************"<<endl;

cout<<"1. Fortune Cookie saying."<<endl;
cout<<"2. Ancient Proverb."<<endl;
cout<<"3. Quit"<<endl;
cin>>number;
if (number == 3); //Not Quitting Correctly?
//Not Repeating the Selection Outputs?
}
}


I am aware that the current line of code will not output what I want, and that the rand function and statements of the second selection have yet to be implemented.

Help would be much appreciated!
It would be nice, wouldn’t it?

I had a nice answer all typed out for you on the last thread for this you created, but after you deleted it, my efforts were lost.

Sorry.
Last edited on
Hello Dylanblitz,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

It makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



Your program is good through the menu down to cin>>number;

After that it is not going to do what you want.

What I would do is create a vector of "std::string"s to hold the messages. One for each category then you could use "rand()" to choose which message to output.

A do/while loop may work better than a while loop for what you want unless you have to use a while loop.

Your first two while loops are not really needed. An if statement would do the same thing.

The last while loop may work, but it is lacking some code to do what you need.

A quick thought here:
1
2
if (number == 3)
    break;  // <--- to leave the while loop. 

The semi-colon you have at the end of the if statement makes it a single statement and anything that might follow would not be part of the if statement.

Hope that helps,

Andy
Topic archived. No new replies allowed.