2013-05-29 135 views
0

我想制作一个程序,用户输入几个名字,然后选择一个随机名称。但是,我无法弄清楚如何获取字符串。我希望每个字符串都分配给一个int,然后当选择一个int时,字符串也是如此。请帮帮我。C++ - while循环,字符串和整数

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

'的std ::矢量'' – johnchen902

+2

空隙randName();'中主要是解决'最棘手parse' – billz

回答

1

你可以使用std::vector<std::string>来存储你的名字,并用int作为索引。并随后使用随机选择其中一个名称。

1

你会想要某种容器来存储你的名字。一个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"); 
} 
+0

感谢问题 – sth8119