gpt4 book ai didi

c++ - while 循环、字符串和整数

转载 作者:行者123 更新时间:2023-11-28 03:16:12 24 4
gpt4 key购买 nike

我想制作一个程序,用户输入几个名字,然后随机选择一个名字。但是,我无法弄清楚如何获取要选择的字符串。我想将每个字符串分配给int,然后在选择int时,字符串也是如此。请帮助我。

    #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");
}

最佳答案

您需要某种容器来存储您的姓名。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 "";
}

正如 billz 提到的,您的 main() 也有问题。您想要调用您的函数,所以您不需要void 关键字。这个新函数还会返回一个字符串,所以它确实很有用。

int main()
{
std::string myRandomName = randName();
system("PAUSE");
}

关于c++ - while 循环、字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16803571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com