簡體   English   中英

收到“字符串下標超出范圍”錯誤

[英]Recieving "string subscript out of range" error

執行此任務時,我將信息解析為結構體,並且在嘗試測試時不斷收到錯誤消息,提示“字符串下標超出范圍”。 無法弄清楚我哪里出錯了。

這是結構

struct baby_type {

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

這是我的功能

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;
}

如果創建空的 std::string 對象,然后將字符分配到特定位置。 std::strings 不能那樣工作。 在你的第一個 while 循環中,使用

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

'1' 是必要的,因為沒有簡單的 std::append 只用一個字符作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM