Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 接收“字符串下标超出范围”错误_C++_Parsing_Debugging_Compiler Errors_Runtime Error - Fatal编程技术网

C++ 接收“字符串下标超出范围”错误

C++ 接收“字符串下标超出范围”错误,c++,parsing,debugging,compiler-errors,runtime-error,C++,Parsing,Debugging,Compiler Errors,Runtime 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:

在执行此赋值时,我将信息解析到结构中,并且在尝试测试时不断收到一个错误,称字符串下标超出范围。我想不出哪里出了错

这是结构图

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对象,然后将字符分配到特定位置。字符串不是这样工作的。 在第一个while循环中,使用

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

“1”是必需的,因为没有简单的std::append,只有一个字符作为参数。

在检查行的长度之前,您从行中读取了很多字符。乍一看,如果line.ati调用中包含的逗号少于100个,则该调用将从行尾开始运行,因为while循环仅在您读取多个逗号时终止,而不是在您到达行尾时终止。请添加@Rene。您正在增加i变量,其中一条指令超出范围。你必须限制它。检查代码后,我还确定line year.atDigitOfOccurences=line.ati;也会造成问题。请试着重写一下。推回怎么样?好的,这个可以用。