Reputation: 413
i want to make a program where the user enters a few names, then a random name is picked. but, i can't figure out how to get the string to be picked. i want to have every string assigned to an int, then when an int is choosen, so is the string. please help me.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void randName()
{
string name;//the name of the entered person
cout << "write the names of the people you want.";
cout << " When you are done, write done." << endl;
int hold = 0;//holds the value of the number of people that were entered
while(name!="done")
{
cin >> name;
hold ++;
}
srand(time(0));
rand()&hold;//calculates a random number
}
int main()
{
void randName();
system("PAUSE");
}
Upvotes: 0
Views: 9054
Reputation: 5334
You could use a std::vector<std::string>
to store your names and later use the random to pick one of the names by index.
Upvotes: 1
Reputation: 18848
You'll want some sort of container to store you names in. A vector
is perfect for this.
std::string RandName()
{
std::string in;
std::vector<std::string> nameList;
cout << "write the names of the people you want.";
cout << " When you are done, write done." << endl;
cin >> in; // You'll want to do this first, otherwise the first entry could
// be "none", and it will add it to the list.
while(in != "done")
{
nameList.push_back(in);
cin >> in;
}
if (!nameList.empty())
{
srand(time(NULL)); // Don't see 0, you'll get the same entry every time.
int index = rand() % nameList.size() - 1; // Random in range of list;
return nameList[index];
}
return "";
}
As billz mentioned, you also have a problem in your main()
. You want to be calling your function, so you don't want the void
keyword. This new function will also return a string, so that it's actually useful.
int main()
{
std::string myRandomName = randName();
system("PAUSE");
}
Upvotes: 1