Random pick???

0 lewis owen · July 26, 2014
Hi there,
           I am making a short game as i am a beginner where you ask the computer a question and it tells you a random answer like an 8 ball...... Here is the code:
#include <iostream>

#include <stdlib.h>

using namespace std;

int main()
    cout << "Welcome to my Crystal Ball Game\nIf you want to know how to play simply write rules\nIf you want to play type play.\nOr if you wish to exit write exit." << endl;
    string ruleplay;
    cin >> ruleplay;

    if (ruleplay == "rules"){
        cout << "\nRULES" << endl;
        cout << "You write into the computer a question and it answers.\nNotice this is just a game of predictions they're not real!\nWrite play to play.\nOr write exit to exit." << endl;
        cin >> ruleplay;
    if (ruleplay == "exit"){

    if (ruleplay == "play"){
            cout << "Ask a question: " << endl;
            string question;
            cin >> question;

    return 0;

If i wrote out a list of questions, how could I get the computer to pick a random one and cout it to the user?

Post a Reply


Oldest  Newest  Rating
0 lewis owen · July 27, 2014
I have figured it out by using an array.


       const string answers[4] = { "Can not for tell now"
                                          "Never", "Not possibly",                                            ,"Definitely" };
string answer = answers[rand() % 4];

cout << answer << endl;
+1 Franz Schmidt · July 27, 2014
Well done but it gets a little more difficult if you don't want start counting from 0.
And please use code tags :angel:
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator