【发布时间】:2015-09-29 02:52:44
【问题描述】:
好的,我现在可以正常运行了,我已经编辑了这篇文章和下面的代码,以反映更新后的正常工作代码。
将文本文件中的 50 个单词读入字符串数组
-
程序将使用随机数:
a.- 它将生成一个介于 2 到 7 之间的随机数,用于选择要在句子中使用的单词
b.- 它将生成一个随机数来选择单词。数字将在 0 到 49 之间,因为这些是单词在数组中的位置
它会在屏幕上显示句子。
提前感谢您的任何建议
#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();
}
【问题讨论】: