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

名前を保存するための何らかのコンテナが必要になるでしょう。これには 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 に答える
1

a を使用しstd::vector<std::string>て名前を保存し、後で random を使用してインデックスによって名前の 1 つを選択できます。

于 2013-05-29T00:25:40.660 に答える