使用2D向量的C ++向量下标错误

时间:2014-11-23 21:35:03

标签: c++ vector

我在尝试编译时遇到了向量下标错误。我的代码如下。该程序旨在读取文本文件,并将问题和答案检索到矢量中,然后从文本文件中的10个中选择5个随机问题,然后在屏幕上显示第一个问题。每个问题在文本文件中有6行:问题为1,可能答案为4,正确答案为1。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <ctime>

//FUNCTION PROTOTYPES
void SetQuestions(std::vector<std::vector<std::string>> &questionsChosen);

int main()
{
    //seed random number generator
    srand(static_cast<unsigned int>(time(0))) ;

    //RETRIEVE QUESTIONS FROM FUNCTION
    std::vector<std::vector<std::string>> questionsChosen;
    SetQuestions(questionsChosen);

    //Test if stored correctly
    std::cout << questionsChosen[0][0];


    return 0;
}

void SetQuestions(std::vector<std::vector<std::string>> &questionsChosen)
{
    //RETRIEVES ALL Q&A AND PUTS INTO 2 DIMENSIONAL VECTOR - questionsAll

    std::vector<std::vector<std::string>> questionsAll;
    std::ifstream fromFile("QA.txt");
    for (; fromFile.eof();)
    {
        std::vector<std::string> question;
        for (int i = 0; i < 6; i++)
        {
            std::string line;
            std::getline(fromFile, line);
            question.push_back(line);
        }
        questionsAll.push_back(question);
    }

    fromFile.close();

    //GENERATE RANDOM NUMBERS TO CHOOSE 5 RANDOM QUESTIONS

    int c1 = rand() % 9;

    int c2 = rand() % 9;
    //prevent duplicates
    while (c2 == c1)
    {
        c2 = rand() % 9;
    }

    int c3 = rand() % 9;
    while ((c3 == c1) || (c3 == c2))
    {
        c3 = rand() % 9;
    }

    int c4 = rand() % 9;
    while ((c4 == c1) || (c4 == c2) || (c4 == c3))
    {
        c4 = rand() % 9;
    }

    int c5 = rand() % 9;
    while ((c5 == c1) || (c5 == c2) || (c5 == c3) || (c5 == c4))
    {
        c5 = rand() % 9;
    }

    //COPY CHOSEN QUESTIONS INTO NEW ARRAY


    questionsChosen.push_back(questionsAll[c1]);
    questionsChosen.push_back(questionsAll[c2]);
    questionsChosen.push_back(questionsAll[c3]);
    questionsChosen.push_back(questionsAll[c4]);
    questionsChosen.push_back(questionsAll[c5]);

}

0 个答案:

没有答案