instance of 'std::out_of_range' problem

this is the message I get when I compile my program:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
I still haven't been able to put my finger on where the problem is. Here is my code:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

struct album
{
string albumN,year,songL[30],song[30];
int c;
};

void sSort(string ar[], string arL[], int elems)
{
int swaps = 1,j;
while(swaps)
{
swaps = 0;

for(j = 0; j < elems-1; j++)
{
if(arL[j].compare(arL[j+1]) == 1)
{
swap(arL[j],arL[j+1]);
swap(ar[j],ar[j+1]);
swaps = 1;
}
}
}
}

void sort_albums( struct album beatles[], int c)
{
int swaps = 1,j;
while(swaps)
{
swaps = 0;
for(j = 0; j < c-1; j++)
{
if(beatles[j].albumN.compare(beatles[j+1].albumN) == 1)
{
swap(beatles[j],beatles[j+1]);
swaps = 1;
}
}
}
}


int main ()
{
const int size = 5;
string line,ar[200];
struct album beatles[size];
int len,i = 0,x = 0;

ifstream beatlesData ("beatles.cpp"); //opening the file.

if (beatlesData.is_open()) // if the file is open
{
while (!beatlesData.eof()) // while the end of file is NOT reached
{
for(x = 0; x < size; x++)
{

// get album name
getline(beatlesData,line);
beatles[x].albumN = line;

// get album year
getline(beatlesData,line);
beatles[x].year = line;
beatles[x].c = 0;

// get the first song
getline(beatlesData,line);

// get the rest of the songs
// get album songs
do
{
len = line.length();
beatles[x].song[i] = line;
beatles[x].songL[i] = beatles[x].song[i].substr(4,len);
beatles[x].c++;
getline(beatlesData,line);
i++;
} while(line[0] != '=' && !beatlesData.eof());

//sort songs

sSort(beatles[x].song, beatles[x].songL, i);
// reset the number of songs to 0
i = 0;
}
}

sort_albums(beatles, 5);

for(int y = 0; y < size; y++)
{
cout << beatles[y].albumN << endl;
cout << beatles[y].year << endl;
for(int x = 0; x < beatles[y].c; x++)
{
cout << beatles[y].song[x] << endl;
}
cout << "==============================" << endl;
}
beatlesData.close(); //closing the file
}

else cout << "Unable to open file"; //if the file is not open output
return 0;
}
> beatles[x].song[i].substr(4,len);

The exception would be thrown if the string is not long enough; ie. beatles[x].song[i].size() is less than 4.
I increased the size but am still getting the same error. Perhaps my size is still not large enough?
Why not just check that the string is long enough before looking for the substring?
Topic archived. No new replies allowed.