为什么这个函数输出一个单词多次而不是一次
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;
}
}
}
我的程序应该从外部文件列表中提取一个随机单词并一次性输出,但实际上,它基本上是用所选单词覆盖列表的其余部分。
这是一个Hangman游戏,用户将不得不猜测,所以它只需要一次。谁能帮我三天后到期吗。
移动此:
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;
相关文章:
- 如何在 Eclipse 中一次从多个源文件进行构建
- 系统调用:一次和多次,哪个更好?
- 一次连接多个C++字符串?
- 如何一次更改多个qlineedit的属性
- 组合宏定义以一次获得多个定义 [avr C++]
- C++错误,隐 <function-style-cast> 式要求使用模板化类一次调用多个构造函数的多个转换
- 在 Cocos2d-x 中一次使用多个精灵表
- 一次发布多个数据
- C 列表一次由多个字段排序
- cmake-一次针对多个体系结构,而无需在构建之间进行手动清理
- 在一个位集中一次设置多个位
- 使用 GLFW 一次处理多个键输入
- 随机打印程序,尽管 sleep() 功能,一次打印多个输出
- 在 Eclipse 上,有没有办法一次修改多个包含路径
- 使用一个 QPainter 一次绘制多个输出:SVG 和 QImage
- 如何一次编译多个独立的CPP文件
- 快板 5 一次播放多个样本
- 如何一次创建多个线程
- 如何使用c ++ / c从Windows命令行一次运行多个命令
- 如何使"strtok function"一次使用多个令牌字符串? 函数指针会解决这个问题吗?