简体   繁体   English

为什么这个 function 输出一个字多次而不是一个?

[英]why is this function outputting a word multiple times instead of one?

#include <iostream>
#include <string>//needed to make string array
#include <fstream>//Needed for redaing in from external file
#include <cstdlib>//needed for rand() function (for random word)
#include <ctime>//needed for time() funtion to seed rand()
using namespace std;

void wordPick();
int main()
{
    wordPick();

    return 0;
}

void wordPick()//reads in external file and puts it in an array for a library of words to randomly choose
{
    char secretWord;
    srand(time(0));
    ifstream inFile("randwords.txt");
    if(inFile.is_open())
    {
        string wordlist[10];
        for(int i = 0; i < 10; ++i)
        {
            inFile >> wordlist[i];
            srand(time(0));
            string secretword = wordlist[rand() % 10];
            cout<< secretword << endl;
        }
    }
}

my program is supposed to take a random word from an external file list and output it one time but instead, it is basically writing over the rest of the list with the chosen word.我的程序应该从外部文件列表和 output 中获取一个随机词,但它基本上是用所选词覆盖列表的 rest。

This is for a game of Hangman that the user will have to guess so it needs to be only once.这是一个刽子手游戏,用户必须猜测,所以它只需要一次。 Can anyone help its due in 3 days.任何人都可以帮助它在 3 天内到期。

Move this:移动这个:

srand(time(0));
string secretword = wordlist[rand() % 10];
cout<< secretword << endl;

outside of your for loop, and remove the redundant call to srand(time(0)) :在您的for循环之外,并删除对srand(time(0))的冗余调用:

for(int i = 0; i < 10; ++i)
{
    inFile >> wordlist[i];
}

string secretword = wordlist[rand() % 10];
cout<< secretword << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM