I am looking to access a completely random line of a small text file, and import the same line in another text file in a C++ program. I need to do this fairly simply, I am a beginner to C++ programming. I will include main.cpp. If you need the other .cpp or the .h, just let me know, I will post it.
Main.cpp:
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include "getQuestion.h"
using namespace std;
int main() {
int mainMenuChoice;
ifstream Bibliography;
//string easyBib;
string easyBib;
ifstream inputFile;
cout << "Quiz Menu\n\n";
cout << "1. Play Game!\n";
cout << "2. Bibliography\n";
cout << "3. Developer Info\n";
//cout << "4. Admin Menu\n";
cout << "4. Exit\n";
cout << "Menu Choice: ";
cin >> mainMenuChoice;
switch (mainMenuChoice) {
case 1:
//int getQuestion(string Q,A);
//cout << Q;
break;
case 2:
inputFile.open("Bib.rtf");
inputFile >> easyBib;
cout << easyBib << endl;
break;
case 3:
cout << "Program made by: XXXX XXXXXXXX" << endl;
cout << "XXX. XXXXXXX'X Period 4 Social Studies Class" << endl;
break;
/*case 4:
break;*/
case 4:
cout << "Thank you for playing!" << endl;
return(0);
default:
cout << "Sorry, Invalid Choice!\n";
return(0);
}
return(0);
}
The easiest solution would be to read the entire file line by line (using
getline) into avector<string>. Then it’s trivial to select a random element from that vector.You can read a line from an input stream like this:
It returns a reference to the stream, which can be tested directly for error. So this is easily turned into a loop like this:
Now you can use the
sizefunction ofvectorto determine how many lines you have read, and then choose a random one.Of course, you need to know that there will be fewer than
RAND_MAXlines in your file. Otherwise you’ll have to combine multiple calls torandjust to cover the range.