c++ - 为什么这个函数多次输出一个单词而不是一个?
问题描述
#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;
}
}
}
我的程序应该从外部文件列表中获取一个随机单词并输出一次,但实际上它基本上是用所选单词覆盖列表的其余部分。
这是一个刽子手游戏,用户必须猜测,所以它只需要一次。任何人都可以帮助它在 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;
推荐阅读
- ruby-on-rails - 在将 pg 列从文本迁移到二进制 (bytea) 的 Rails 迁移中,如何解决“bytea 类型的无效输入序列”?
- java - RecyclerView - 将最后一项移动到中间?
- ios - IOS ATT Apptracking透明度指南
- python - SELENIUM WEB 驱动程序 - 单击过滤器
- spring-boot - 如何实现正确的自定义异常处理程序?
- javascript - 比较两个数组并插入空值
- laravel - 如何让我的图像更新和删除
- javascript - 在 React 中加载 DOM 后定义/初始化变量的最佳方法是什么?
- reactjs - TypeScript 中的 Redux Toolkit:添加时间戳的 createAction 抽象
- firebase - 凭据无效 - Unity Firebase