读取结构数组时出错

Out of Range Error When Reading to Struct Array

本文关键字:出错 数组 结构 读取      更新时间:2023-10-16

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

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

这是我收到的错误消息。

您面临的特定错误是dataLine的长度为零,并且您正在尝试子字符串。此处描述了异常:http://www.cplusplus.com/reference/string/string/substr/

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

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