简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM