Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.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++_Arrays_Struct_Outofrangeexception - Fatal编程技术网

C++ 读取结构数组时出现超出范围错误

C++ 读取结构数组时出现超出范围错误,c++,arrays,struct,outofrangeexception,C++,Arrays,Struct,Outofrangeexception,因此,我正在为数据库存储编写一个程序,第一步是将信息从文本文件加载到结构数组。但是,我在读/写过程中收到一条错误消息,表示程序将进入一个超出范围的实例 while (!inFile.eof()) { getline(inFile, dataLine); //saves the line of the file into a string a[i].name = dataLine.substr(0, 17); // 18 a[i].author

因此,我正在为数据库存储编写一个程序,第一步是将信息从文本文件加载到结构数组。但是,我在读/写过程中收到一条错误消息,表示程序将进入一个超出范围的实例

while (!inFile.eof())
{
    getline(inFile, dataLine);              //saves the line of the file into a string

    a[i].name = dataLine.substr(0, 17); // 18
    a[i].author = dataLine.substr(19, 33); // 15
    a[i].vol = dataLine.substr(35, 60); // 26
    a[i].pub = dataLine.substr(62, 77); // 16
    a[i].year = dataLine.substr(79, 82); // 4
    a[i].price = dataLine.substr(84, 91); // 8
    a[i].copies = dataLine.substr(93, 96); // 3


    i++;    //moves through the array after each line.
    count++;    //counts how many lines/items there are in the file entered for the program
}
我已经把问题缩小到这一部分,但我似乎不知道是什么导致它出错

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::substr: __pos (which is 19) > this->size() (which is 0)
Aborted

这是我收到的错误消息。

您面临的具体错误是,
数据线的长度为零,并且您正在尝试使用子字符串。例外情况如下所述:

对字符串的长度进行额外检查可以解决此问题

if (dataLine.size() >= 97) {
    ...
}

首先也是最重要的。解决这个问题。第二,更新您的问题,使其包含重现问题的内容,包括重现问题所需的任何输入。@WhozCraig这可能是错误的原因。因此,循环不会在文件末尾停止。它会执行一个额外的
getline()
,返回一个零长度字符串,然后
dataLine.substr(19,33)
会得到一个错误。更具体地说,每个substr调用都应该确保
dataLine.length()
至少与子字符串请求的右端一样宽,否则它就没有意义了。至少,它应该检查
dataLine.length()>=97
,而不仅仅是大于零。