从文件中输入单词列表然后选择一个随机单词?

时间:2014-11-27 17:38:00

标签: c++ arrays file random input

所以我正在处理一个Hangman游戏,因为单词是在一个文本文件中,我想把这些单词放入一个数组中,然后从数组中选择一个随机的作品并将其用作我的秘密单词。任何帮助都会很棒。谢谢!

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>

using namespace std;

const int MAX_NUMS = 200;   // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";


//function prototypes
char   inputLetter();
int    findChar(char letter, string word);
string getGuessedWord(string secretWord, string lettersGuessed);

//main function
int main()
{
    string word;                    // holds one word from input file
    string secretWord;              // holds secret word to be guessed
    string words[MAX_NUMS];         // holds list of words from input file
    int randomValue;                // holds index of secret word
    int count = 0;                  // holds number of words in the file

    // Declare an ifstream object named myFile and open an input file
    string line;

    ifstream myfile ("p4words.txt");

    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line);

            cout << line << endl;
        }
         myfile.close();
    }

    else cout << "Unable to open file";

    // Input words from a file into words array
    {
        ifstream myfile("p4words.txt");

        if(myfile.is_open())
        {
            string words[MAX_NUMS];

            for(int count = 0; count < MAX_NUMS; count++)
            { 
                myfile >> words[count];
            }
        }

    }


    cout << count << " words loaded." << endl;

    srand(static_cast<unsigned int>(time(0)));

    // Select a secret word

1 个答案:

答案 0 :(得分:0)

如果你有C ++ 11,请使用#include <random>。你可以做点什么

#include <random> 
...

std::random_device rd; // source of randomness
std::mt19937 rng(rd()); // seed random number engine
std::uniform_int_distribution<std::size_t> uid(0,words.size() - 1);
std::size_t sample = uid(rng); 

std::cout << words[sample] << std::endl; // uniform randomly chosen word

请参阅http://ideone.com/uD04b9

上的完整示例

如果您没有符合C ++ 11的编译器,则必须使用旧的srand()/rand()函数来模拟统一分布,例如:

srand(static_cast<unsigned int>(time(0)));
sample = static_cast<std::size_t>(rand() % words.size()); // uniform distribution
std::cout << words[sample] << std::endl; // uniform randomly chosen word