为什么这个函数输出一个单词而不是一个单词?

问题描述 投票:1回答:1
#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;
        }
    }
}

我的程序应该从外部文件列表中提取一个随机单词并输出一次,但实际上,它基本上是使用所选单词覆盖列表的其余部分。

这是针对Hangman游戏,用户必须猜测,因此只需一次。任何人都可以在3天内帮助其付款。

c++
1个回答
2
投票

移动此:

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

for循环之外,并删除对srand(time(0))的多余调用:

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

string secretword = wordlist[rand() % 10];
cout<< secretword << endl;
© www.soinside.com 2019 - 2024. All rights reserved.