M.I
M.I

Reputation: 11

C++ out of range error, error described in the content below

I'm getting a std::out_of_range exception running the code below. Here is the exact error text:

Unhandled exception at 0x7690A6E2 in Student Project.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00AFF2BC.

I don't know what is wrong with my code. Is it the way the vector is defined? Is anything wrong with the syntax of the vector?

How can I fix the problem so that the exception no longer occurs?

void Roster::parseInput(string rawInput){
    std::vector<string> dataHolders;
    std::stringstream inputSStream(rawInput);

    while (inputSStream.good())
    { // Parse the string on every comma
        string input;
        getline(inputSStream, input, ',');
        dataHolders.push_back(input);
    }

    string studentID = dataHolders.at(0);
    string firstName = dataHolders.at(1);
    string lastName = dataHolders.at(2);
    string email = dataHolders.at(3);
    int age = stoi(dataHolders.at(4)); 
    int DayInCourse1 = stoi(dataHolders.at(5));
    int DayInCourse2 = stoi(dataHolders.at(6));
    int DayInCourse3 = stoi(dataHolders.at(7));
    degreeProgram DegreeProgram = convert(dataHolders.at(8)); //(I was told this could be the problem)
    string personalInformation = dataHolders.at(9);

    add(studentID, firstName, lastName, email, age, DayInCourse1, DayInCourse2, DayInCourse3, 
    DegreeProgram, personalInformation);
}

degreeProgram Roster::convert(string str)
{ //Converting string type to enum

    if (str == "SECURITY") return  SECURITY;

    else if (str == "NETWORK") return NETWORK;

    else if (str == "SOFTWARE") return SOFTWARE;

    else return INVALID;
        
}

Upvotes: 1

Views: 653

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595712

You are getting an std::out_of_range exception at runtime. That is likely being raised by one of the dataHolders.at() calls:

If pos is not within the range of the container, an exception of type std::out_of_range is thrown.

Which means your vector does not hold as many string elements as you are expecting. So double-check that the value of your rawInput parameter is correct. You can check the size() of the vector after the loop is finished, before accessing the string elements, eg:

while (...)
{
    ...
    dataHolders.push_back(input);
}

if (dataHolders.size() >= 10)
{
    string studentID = dataHolders[0];
    ...
}
else
{
    // dataHolders has too few strings, do something else!
    ...
}

On a side note, your while loop should look more like this instead:

// Parse the string on every comma
string input;
while (getline(inputSStream, input, ','))
{
    dataHolders.push_back(input);
}

Upvotes: 2

L.C.
L.C.

Reputation: 1145

I would say you need to make sure your dataHolders has the correct number of entries (10) before trying to read them.

Upvotes: 1

Related Questions