打印字符串向量的内容
Printing contents of String Vector
好的,我几乎得到了这个工作,但我卡住了b.的第二部分,让它在数组中显示那个位置的单词。这是我需要它做的事情的列表。
-
从文本文件中读取50个单词到字符串数组
-
程序将使用随机数:
。-它将生成一个2到7之间的随机数,用于选择要在句子中使用的单词
b。-它将生成一个随机数,用于选择单词。数字将在0到49之间,因为这些是数组
中单词的位置。 将句子显示在屏幕上
提前感谢您的建议
#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;
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>