[英]c++ - while loop, strings, and ints
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. 我希望将每个字符串分配给一个int,然后选择一个int时,字符串也是如此。 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");
}
you can use a std::vector<std::string>
to store your names with the int's as index. 你可以使用std::vector<std::string>
来存储你的名字,并以int作为索引。 and later use the random to pick one of the names. 然后使用随机选择其中一个名称。
You'll want some sort of container to store you names in. A vector
is perfect for this. 你需要某种容器来存储你的名字。 vector
是完美的。
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()
. 正如billz所提到的,你的main()
也有问题。 You want to be calling your function, so you don't want the void
keyword. 您想要调用您的函数,因此您不需要void
关键字。 This new function will also return a string, so that it's actually useful. 这个新函数也将返回一个字符串,因此它实际上很有用。
int main()
{
std::string myRandomName = randName();
system("PAUSE");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.