gpt4 book ai didi

c++ - 为什么此函数多次输出一个单词而不是一个单词?

转载 作者:行者123 更新时间:2023-12-02 10:03:07 25 4
gpt4 key购买 nike

#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天内提供帮助。

最佳答案

移动这个:

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;

关于c++ - 为什么此函数多次输出一个单词而不是一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com