2

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);
}
4

1 回答 1

3

最简单的解决方案是逐行(使用getline)将整个文件读取到vector<string>. 然后从该向量中选择一个随机元素是微不足道的。

您可以像这样从输入流中读取一行:

string line;
getline( inputFile, line );

它返回对流的引用,可以直接测试错误。所以这很容易变成这样的循环:

vector<string> lines;
for( string line; getline(inputFile,line); )
{
    lines.push_back(line);
}

现在您可以使用 的size功能vector来确定您阅读了多少行,然后随机选择一个。

size_t iRandLine = rand() % lines.size();
string randomLine = lines[iRandLine];
cout << "Line " << (iRandLine+1) << ": " << randomLine << endl;

当然,您需要知道RAND_MAX文件中的行数将少于行数。否则,您必须将多个调用组合起来rand才能覆盖范围。

于 2012-12-19T03:13:31.460 回答