lundi 19 février 2018

C++ rand() function acting really weirdly [duplicate]

I'm currently learning C++, and to practice a bit I'm coding a little game, that picks a word in a file, then changes its characters positions randomly so the player has to find the word (e.g "nalep": the user has to find the word "plane").
The game in itself works, but I'm getting a weird issue while trying to pick a random word from the file.
This is how my algorithm does the job:
- Counts the lines of the file
- Picks a random number between 1 and the number of lines
- Sets the position in the file back to the starting - Reads each line up to the good one

The problem I have is that each time I play the game, the same word is taken. You may say I'm using rand() the wrong way, but rand() only picks an other number when I change the content of my file..! (I can't even figure how these two elements are related)

Example content of the file:

game
book
file
computer

My code:

void playSecretWord() {

    ifstream file("C:\\Users\\chris\\Desktop\\word.txt"); // Opens file

    if (file) {
        string word; // Contains the word to find

        // Counts lines
        int count(0);
        while (getline(file, word)) { count++; } // Reads all lines and adds 1 to count each line

        // Goes back to the starting of the file
        file.clear();
        file.seekg(ios::beg);

        int random = rand() % count + 1; // Picks a random number that corresponds to a line

        for (int i(1); i <= random; i++) { getline(file, word); } // Reads each line up to the chosen one

        upper_string(word); // Capitalizes the word
        string goodAnswer = word; // Stores the word

        string newWord(""); // Word randomly written
        while (word.size() > 0) {
            int characterIndex = rand() % word.size(); // Takes a random character from the initial word
            newWord += word[characterIndex]; // Adds it
            word.erase(characterIndex, 1); // Removes it from the initial word
        }

        cout << "(" << random << ") What is this word : " << newWord << endl;

        string answer("");
        int i(0);
        while (answer != goodAnswer) {
            ++i; // Adds 1 to the number of tries
            cout << i << " > "; // Prints the number of the try
            cin >> answer; // Asks for the answer
            upper_string(answer); // Capitalizes the answer so it can be compared to the good answer (that has been capitalized too)
        }

        cout << "Good answer ! Tries : " << i << endl;

    }
    else {
        cout << "Error while opening file. Make sure the file exists." << endl;
    }
}

Thanks :)




Aucun commentaire:

Enregistrer un commentaire