Debug Assertion Failed!

I am new to C++ and this forum. When I was working on my assignment, a 'string subscript out of range' error keeps occuring in Line 1441.

The partial code is as follow:
1
2
3
4
5
6
7
8
9
string naming(string lines[],string name[]) {
	for (int i = 0 ; i<= 99 ; i++) {
		int  j = 0;
    while (!(lines[i][j] >= '0' && lines[i][j] <= '9')) {
		j++; } 
   name [i] = lines[i].substr(0,j-2);
	}
	return name[100];
}


The above function inputs an array(lines) input from a text file storing at most 100 students' names and other integers(separated by a space), what I want is to place all the names in another arrays (name). While in debugging, the mentioned error keeps occuring. How could I solve it? If you would require further information, please let me know.

Thank you so much.
Last edited on
Each string has a particular length, for example
lines[i].size()

Your code doesn't check that the index j is within this limit.

Also, you say the array will have at most 100 lines, but the loop attempts to process the full 100 lines (even if that line is empty).
Last edited on
Thank you for your answer. I tried to solve the problem by declaring a global variable to count the number of lines in the getline function when I input the file into array, lines. Also, I adjusted the code such that it become:
1
2
3
4
5
6
7
8
9
10
11
12
string naming(string lines[],string name[]) {
	for (int i = 0 ; i<= number_of_lines ; i++) {
		int  j = 0;
    while (!(lines[i][j] >= '0' && lines[i][j] <= '9')) {
		j++;
    if (j <= lines[i].length())
	continue;
	else break;} 
   name [i] = lines[i].substr(0,j-2);
	}
	return name[100];
}


However, this time, when I debug, it says ' an unhandled win32 exception occured in (my programme cpp file)[3800].
Maybe like this, test the string length before accessing its contents.
And notice < rather than <=
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string naming(string lines[],string name[]) 
{
    for (int i = 0 ; i < number_of_lines ; i++) 
    {
        int  j = 0;
        
        while ((j < lines[i].length()) && (!(lines[i][j] >= '0' && lines[i][j] <= '9'))) 
        {
            j++;
        }
        
        name [i] = lines[i].substr(0,j-2);
    }
    return name[100]; // not sure about this line ????
}
Last edited on
Topic archived. No new replies allowed.