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 only 2 custom functions. The first function is to get a random number between 0-4 and display that index of the vector. The second is a function to display 70 newlines to clear the screen. To get a random index I use the srand and rand functions. The first function srand is used to seed the rand function. To get a number between 0-4 I used the expression (rand() % 4) which will produce 1 number between 0 and 4. In the main of my program I create a infinite while loop and use the usleep function to sleep the program after each run. I used this function so there was time to read each phrase.
// Display Random String // C++ Example // www.TullyRankin.com #include#include #include #include #include #include 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; }