C++ Random String

Posted by Tully on Fri 02 July 2010

Yesterday I was working with vectors and pointers. I decided to create a simple script to display random phrases for fun.

The code I wrote uses 2 custom functions.

The first function is used to get a random number between 0 and 4 and display that index of the phrases vector. The second is used to print 70 newline characters to clear the screen.

To get a random index I use the srand and rand functions.

The function srand is used to seed the rand function.

To get a number between 0 and 4, I use the result of the expression (rand() % 4). This will return a random number between 0 and 4.

In the main method of the program I create an infinite loop. I use the usleep function to sleep the program after each phrase is displayed.

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <stdlib.h>
#include <ctime>
using namespace std;

string randomPhrase(const vector & p);
void clearScreen();

int main()
{
    vector phrases(4);
    phrases[0] = "The more I C, the less I see.";
    phrases[1] = "Backups? We don’t need no stinking backups.";
    phrases[2] = "Avoid the Gates of Hell. Use Linux";
    phrases[3] = "When you say "I wrote a program that crashed Windows",
                 "people just stare at you blankly and say "Hey, I got ",
                 "those with the system, *for free*";

    clearScreen();

    while (true)
    {
        cout << randomPhrase(phrases) << endl;
        usleep(5000000);
        clearScreen();
    }

    return 0;
}

string randomPhrase(const vector & p)
{
    int size = p.size();
    srand(time(NULL));
    return p[rand() % 4];
}

void clearScreen()
{
    for (int i = 0; i < 75; i++)
        cout << endl;
}