所以我感到无聊,并决定我想做一个刽子手游戏。当我第一次使用C ++时,我在高中时做过这样的作业。但这是在我几乎没有几何形状之前,所以不幸的是我在形状或形式上并没有做得很好,并且在学期之后我把所有东西都变成了愤怒。

我正在制作一个txt文档,只是抛出一大堆文字 (即: 测试 爱 hungery flummuxed 搞乱 馅饼 尴尬 您 得到 该 理念 )

所以这是我的问题: 如何让C ++从文档中读取随机单词?

我有一种感觉#include<ctime>将需要,以及srand(time(0));获得某种伪随机选择...但我对如何从文件中取一个随机单词并不是最模糊的...有什么建议吗?

提前致谢!

有帮助吗?

解决方案

这是一个粗略的草图,假设单词由空格(空格,制表符,换行符等)分隔:

vector<string> words;
ifstream in("words.txt");
while(in) {
  string word;
  in >> word;
  words.push_back(word);
}

string r=words[rand()%words.size()];

其他提示

运营商<!> gt; <!> gt;用于字符串将读取1(白色)空格分隔的字。

所以问题是你是想在每次选择一个单词时读取文件,还是想将文件加载到内存中,然后从内存结构中获取单词。没有更多信息,我只能猜测。

从文件中选择一个Word:

// Note a an ifstream is also an istream. 
std::string pickWordFromAStream(std::istream& s,std::size_t pos)
{
    std::istream_iterator<std::string> iter(s);
    for(;pos;--pos)
    {    ++iter;
    }

    // This code assumes that pos is smaller or equal to
    // the number of words in the file
    return *iter;
}

将文件加载到内存中:

void loadStreamIntoVector(std::istream& s,std::vector<std::string> words)
{
    std::copy(std::istream_iterator<std::string>(s),
              std::istream_iterator<std::string>(),
              std::back_inserter(words)
             );
}

生成随机数应该很容易。假设你只想要psudo-random。

我建议在记事本中使用标准C文件API创建纯文本文件(.txt)( fopen() fread( ))从中读取。您可以使用 fgets()一次读取每一行

获得纯文本文件后,只需将每行读入数组,然后使用上面建议的方法随机选择数组中的条目。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top