I'm working on an assignment to take data out of a list of names in a .txt document (one on each line, each ending with a comma).
What I want is:
Count how many lines there were
Use the count to define the size of an array to hold the words
Pick two random words from the list and print them.
This is my code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
srand(time(NULL));
int j;
int rand1 = rand() % 5;
int rand2 = rand() % 5;
ifstream myfile ("NAMES.txt");
if (myfile.is_open()) {
myfile.unsetf(ios_base::skipws);
unsigned line_count = count(
istream_iterator<char>(myfile),
istream_iterator<char>(),
'\n');
j = line_count;
cout << j << endl;
string *MN1 = new string[j];
for(int i = 0; i <= j; i++) {
getline(myfile, MN1[i], ',');
}
cout << rand1 << endl;
cout << MN1[rand1] << " " << MN1[rand2] << endl;
}
else {
cout << "Unable to open file" << endl;
}
}
However, there seems to be something going wrong between when the code reads the number of lines, uses that as the size of the array, then prints the random words.
line_countok ?