需要帮助从矢量生成随机字符串

时间:2014-05-25 03:53:09

标签: c++ random vector srand

所以我现在正在阅读Michael Dawson的Beginning C ++ Through Game编程。我很享受它。不过我对他的刽子手版本有疑问。我会提供代码,但有人能够告诉我为什么每次都不会随机选择不同的单词吗?当我编译时,每次都是“猜测”。是因为THE_WORD = words [0] ??如果是这样的话,如果每次都假设它是一个随机词,为什么他会这样做呢。对不起,如果这是一个显而易见的问题而且我没有看到它。谢谢!

 #include <iostream>
 #include <string>
 #include <algorithm>
 #include <ctime>
 #include <vector>
 #include <cctype>

 using namespace std;

 int main()
 {
   const int MAX_WRONG = 8;//max number of incorrect guesses allowed

   vector<string> words;
   words.push_back("GUESS");
   words.push_back("HANGMAN");
   words.push_back("DIFFICULT");

   srand(static_cast<unsigned int>(time(0)));
   random_shuffle(words.begin(),words.end());
   const string THE_WORD = words[0];           //word to guess

   int wrong = 0;                              //number of incorrect guesses
   string soFar(THE_WORD.size(), '-');         //word guessed so far
   string used;                           //letters already guessed

   cout<<"Welcome to Hangman! Good luck!\n";

   while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
   {
    cout<<"\n\nYou have "<<(MAX_WRONG - wrong);
    cout<<" incorrect guesses left.\n";
    cout<<"\nYou've used the following letters:\n"<< used <<endl;
    cout<<"\nSo far, the word is:\n"<<soFar<<endl;

    char guess;
    cout<<"\n\nEnter your guess: ";
    cin>>guess;

    guess = toupper(guess); //make user can enter lower or uppercase
    while (used.find(guess) !=string::npos)
    {
        cout<<"\nYou've already guessed "<<guess<<endl;
        cout<<"Enter your guess: ";
        cin>>guess;
        guess = toupper(guess);
    }
    used += guess;

    if (THE_WORD.find(guess) != string::npos)
    {
        cout<<"That's right!"<<guess<<" is in the word.\n";

        //update soFar to include newly guessed letter
        for (unsigned int i = 0; i < THE_WORD.length(); i++)
        {
            if (THE_WORD[i] == guess)
            {
                soFar[i] = guess;
            }
        }
    }
    else
    {
        cout<<"Sorry, "<<guess<<" isn't in the word.\n";
        ++wrong;
    }
   }

   if (wrong == MAX_WRONG) {
       cout<<"\nYou've been hanged!";
   }
   else
   {
       cout<<"\nYou guessed it!";
   }

   cout<<"\nThe word was "<<THE_WORD<<endl;
   return 0;
}

2 个答案:

答案 0 :(得分:0)

更新:正如我在评论中指出的那样,我的答案部分描述了传递给random_shuffle()方法的迭代器是不正确的。所以我删除了它。

在运行它时,它似乎总是选择项目0,因为在0,1和2之间随机选择可能连续5次变为0 ...然后连续6次变为0次(谁知道?),但经过多次迭代,它将平衡33/33/33。

答案 1 :(得分:0)

简短版本:

#include <random>
...
default_random_engine rand = default_random_engine(static_cast<unsigned int>(time(0)));
shuffle(words.begin(), words.end(), rand);

长版:

std::random_shuffle的两个参数版本的随机源是实现定义的。 LLVM似乎使用__rs_default,并且无法播种__rs_default,因此每次都会获得相同的结果。这对我来说似乎很疯狂,所以希望我错过了一些东西。