Skip to content

Instantly share code, notes, and snippets.

@brandoningli
Last active February 8, 2017 02:01
Show Gist options
  • Save brandoningli/e2b07b279c7fc0032c74375115708a9c to your computer and use it in GitHub Desktop.
Save brandoningli/e2b07b279c7fc0032c74375115708a9c to your computer and use it in GitHub Desktop.
Selects a random entry from a given list of items, like Class Members. Takes data from a text file called 'items.txt' that lists every item, one per line.
/*
Selects a random entry from a given list of items, like Class Members.
items.txt contains the items, one per line.
*/
#include <fstream>
#include <vector>
#include <string>
#include <time.h>
#include <iostream>
#include <Windows.h>
using namespace std;
ifstream fin;
void getRand(vector<string>);
bool again();
int main(){
srand(time(0)); //Seed Random Number Generator
vector<string> names; //Holds items
//Load Items
fin.open("items.txt");
while(!fin.eof()){
string temp;
getline(fin, temp);
if(temp != "")
names.push_back(temp);
}
fin.close();
//Get random item, and keep going as long as the user wants.
bool more = false;
do{
getRand(names);
more = again();
}while(more);
return 0;
}
void getRand(vector<string> names){
char ipt;
int randIdx = rand() % names.size(); //Get random index from 0 to names.size()-1
cout << "\"" << names[randIdx] << "\" was randomly selected." << endl << endl; //Print to console the random item
}
bool again(){
//Ask user to go again. Only accepts 'y', 'Y', 'n', 'N' as vaild inputs.
cout << "Another? y/n: ";
char ipt;
cin >> ipt;
switch(ipt){
case 'y': case 'Y': system("CLS"); return true;
case 'n': case 'N': return false;
default: cout << "INVALID INPUT" << endl; return again();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment