【问题标题】:RNG in loop and printing word from string array循环中的 RNG 并从字符串数组中打印单词
【发布时间】:2015-09-29 02:52:44
【问题描述】:

好的,我现在可以正常运行了,我已经编辑了这篇文章和下面的代码,以反映更新后的正常工作代码。

  1. 将文本文件中的 50 个单词读入字符串数组

  2. 程序将使用随机数:

    a.- 它将生成一个介于 2 到 7 之间的随机数,用于选择要在句子中使用的单词

    b.- 它将生成一个随机数来选择单词。数字将在 0 到 49 之间,因为这些是单词在数组中的位置

  3. 它会在屏幕上显示句子。

提前感谢您的任何建议

#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <array>

using namespace std;

int main() {
ofstream outFile;
ifstream inFile;
const int size = 50; //initiate constant size for array
string word[size]; //initialize array of string
srand(time(0)); //sets timing factor for random variables

int Random2 = rand() % 6 + 2; //determines random value beteen 2 and 7
inFile.open("words.txt");   //opens input text file
if (!inFile.is_open()) { //tests to see if file opened corrected
    exit(EXIT_FAILURE);
}
while (!inFile.eof()) { //Puts file info into string
    for (int i = 0; i < size; ++i)
    inFile >> word[i];
}
for (int i = 0; i < Random2; i++) { //loops through array and generates    second random variable each loop to determine word to print
    int Random1 = rand() % size;
    cout << word[Random1] << " ";
}
cin.get();
}

【问题讨论】:

    标签: c++ arrays string random


    【解决方案1】:
    int generateRandom()
    {
        default_random_engine generator;
        uniform_int_distribution<int> distribution(0, 49);
        int random = distribution(generator);  // generates number in the range 0..49
        return random;
    }
    

    问题是每次调用getRandom() 函数时都会创建一个新的PRNG 实例。因此,每个实例只调用一次,第一个结果总是相同的。

    相反,您希望创建一次实例并多次调用 same 实例。

    default_random_engine generator;
    uniform_int_distribution<int> distribution(0, 49);
    
    for (int i = 0; i < 5; ++i)
    {
        std::cout << distribution(generator) << std::endl;
    }
    

    cout &lt;&lt; words[generateRandom()]

    words 被声明为std::string 类型。使用[] 访问字符串中的单个字符。你在这里期待什么?您是否打算拥有一个字符串数组(即文本文件中的每一行一个字符串)?如果是这样,你想要像std::vector&lt;std::string&gt; words 这样的东西。现在使用words[0] 访问数组中的一个元素,每个元素都是std::string 类型(而不是像以前那样的单个字符)。

    【讨论】:

    • 谢谢,看来我误解了 RNG 实例在调用时是如何工作的,现在这更有意义了。是的,对于字符串,我正在尝试使用从 RNG 创建的数字从 .txt 文件中随机选择 50 个单词之一然后打印。我认为下面的人给出的答案是我真正想到的,使用标记找到每个单词的开头并打印到分隔符。
    【解决方案2】:

    至于打印单个字符,您只打印字符,因为这就是 [] 运算符对字符串的工作方式。您需要对字符串进行标记。见strtok

    【讨论】:

    • 谢谢,我相信 strtok 实际上是我在使用 [ ] 时所想的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多