Search code examples
c++vectorfstream

Getting Run-Time error when trying to Load a file : Vector subscript out of range?


Im making a program for class that manages a Hotel. I have a function that saves all the current information in the program. But When I try to load back that information, the program crashes and says: Vector subscript out of range. I tried debugging, and I found the area where the problem should be (I think I used the debugger correctly?), but im not getting any compiler errors, so I cant figure out whats wrong. Any suggestions?

void Customer::fromFileString(string data)
{
vector<string> field=tokenize(data);
name=field[0];
phoneNumber=field[1]; //<--- DEBUGGER SAYS ERROR IS IN THIS LINE
ccNumber=field[2];
customerID=stringToInt(field[3]);
int numberOfrooms = stringToInt(field[4]);
for(int i=0;i<numberOfrooms;i++)
{
    roomsCheckedInto.push_back(stringToInt(field[5+i]));
}
}

Here is the tokenize function

vector<string> tokenize(string com)
{
istringstream is(com);
vector<string> vs;
string s;
while(!is.eof())
{
    is>>s;
    vs.push_back(s);
}
return vs;
}

Solution

  • It's telling you that field[1] doesn't exist. So for whatever reason, your tokenize function is returning a vector of length 1.