0

我想制作一个程序,用户输入几个名字,然后随机选择一个名字。但是,我不知道如何得到要挑选的字符串。我想将每个字符串分配给一个 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");
    }
4

2 回答 2

1

您可以使用 astd::vector<std::string>来存储您的姓名,然后使用 random 按索引选择其中一个名称。

于 2013-05-29T00:25:40.660 回答
1

你需要某种容器来存储你的名字。Avector非常适合这个。

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");
}
于 2013-05-29T00:28:00.430 回答