-2

Doing this assignment where I parse information into a struct and I keep recieving an error saying "string subscript out of range" when trying to test. Cant figure out where I went wrong.

here is the struct

struct baby_type {

std::string name;
std::vector<int> yearsCount;
    int total;
} ;

here is my function

baby_type Parse_Line(const std::string line )
{

baby_type baby;
std::string name;
std::string year;// = "0000";
std::string total;
int i = 0;
int k = 1;
int LengthOfOccurences = 0;
int DigitOfOccurences = 0;

while (line.at(i) != ',') {
    name[i] = line.at(i);
    i++;
}
baby.name = name;
i++;

while (k < 100) {   
    if (line.at(i) == ',') {
        year.resize(LengthOfOccurences);
        baby.yearsCount.at(k) = std::stoi(year);
        //year = "0000";
        i++;
        k++;
        DigitOfOccurences = 0;
        LengthOfOccurences = 0;
    }
    else {  
        year.at(DigitOfOccurences) = line.at(i);
        i++;
        LengthOfOccurences++;
    }
}

int m = 0;
int LengthOfLine = line.length();

while (i < LengthOfLine) {
    total.at(m) = line.at(i);
    m++;
    i++;
}

baby.total = std::stoi(total);

return baby;
}
  • You're reading a lot of characters from `line` before you check its length. At a glance, it seems that your `line.at(i)` calls will run off the end of `line` if it contains less than 100 commas, since the while loops only terminate when you read a number of commas, not when you reach the end of `line`. – David Scarlett Sep 27 '16 at 05:49
  • Please add @Rene improvement. You are increasing `i` variable and one of this instructions is going out of range. You have to limit it. After checking the code I'm also sure that line `year.at(DigitOfOccurences) = line.at(i);` and also causing problems. Please try to rewrite it. – Fr333du Sep 27 '16 at 07:17

1 Answers1

-1

If you create empty std::string objects and then assign characters to specific positions. std::strings don't work that way. In your first while loop, use

name.append(1,line.at(i));

The '1' is necessary because there is no simple std::append with just a character as parameter.

Rene
  • 2,466
  • 1
  • 12
  • 18