打印字符串向量的内容

Printing contents of String Vector

本文关键字:向量 字符串 打印      更新时间:2023-10-16

好的,我几乎得到了这个工作,但我卡住了b.的第二部分,让它在数组中显示那个位置的单词。这是我需要它做的事情的列表。

  1. 从文本文件中读取50个单词到字符串数组

  2. 程序将使用随机数:

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

    b。-它将生成一个随机数,用于选择单词。数字将在0到49之间,因为这些是数组

  3. 中单词的位置。
  4. 将句子显示在屏幕上

提前感谢您的建议

#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <vector>
using namespace std;
int main() {
    ofstream outFile;
    ifstream inFile;
    string word;
    vector <string> words;
    srand(time(0));
    int Random2 = rand() % 7 + 1;
    inFile.open("words.txt");
    if (!inFile.is_open()) { //tests to see if file opened corrected
        exit(EXIT_FAILURE);
    }
    while (getline(inFile, word)) { //Puts file info into string
        words.push_back(word);
    }
    for (int i = 0; i < Random2; i++) {
        int Random1 = rand() % 49 + 1;
        cout << words[Random1] << endl;
    }
    cin.get();
}

您生成预期范围内随机数的逻辑不正确。

int Random2 = rand() % 7 + 1;

这使得Random2的范围从1到7,包括两个。如果您希望范围是2到7(包括两个),则需要使用:

int Random2 = rand() % 6 + 2;

int Random1 = rand() % 49 + 1;

使Random1的范围从1到49,两者都包括在内。如果您希望范围是0到49(包括两个),则需要使用:

int Random1 = rand() % 50;