所以我正在为数据库存储编写程序,第一步是将信息从文本文件加载到struct数组。但是,在读/写过程中我收到一条错误消息,说该程序进入超出范围的实例。
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
这是我收到的错误消息。
答案 0 :(得分:0)
您面临的具体错误是dataLine
的长度为零,并且您正尝试子串。此处描述了异常:http://www.cplusplus.com/reference/string/string/substr/
对字符串的长度进行额外检查可以解决此问题。
if (dataLine.size() >= 97) {
...
}