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

标签 c++ string loops

我想制作一个程序,用户输入几个名字,然后随机选择一个名字。但是,我无法弄清楚如何获取要选择的字符串。我想将每个字符串分配给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/

相关文章:

javascript - 如何根据选择框值将 div 复制一定次数?

bash while Break 跳出循环而不是循环?

c++ - 错误 LNK2038 : mismatch detected for '_MSC_VER' : value '1800' doesn't match value '1900'

r - R中的字符串匹配算法

python - 如何使用 str.format 禁止换行

bash - 如何迭代文件中的行并将字段读入变量

c++ - 通过引用传递表达式与通过引用传递变量

c++ - 在 gdb 中使用核心转储时,我如何确切知道哪个线程导致了 SIGSEGV?

c++ - output objdump -t的输出中的 ".hidden"是什么意思?

java.util.NoSuchElementException 即使包含 hasMOreTokens