我正在编写一个用cvs文件中的数据填充QTableView的程序。我也将这些数据推送到一个类的对象向量中。我希望能够从文件中捕获任何可能导致出界错误的记录并移动到下一行而不将该记录添加到表或向量中。
这是填充表格的函数:
QString filename = "currentstudents.csv";
QFile file(filename);
file.open(QIODevice::ReadOnly);
int lineindex = 0;
QTextStream input(&file);
while (!input.atEnd()) {
std::vector<QString> newRecord;
QString fileLine = input.readLine();
QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
for (int i = 0; i < lineToken.size(); i++) {
QString value = lineToken.at(i);
newRecord.push_back(value); //this line is where out of bounds error comes from
QStandardItem *item = new QStandardItem(value);
currentStudentsModel->setItem(lineindex, i, item);
}
try
{
//creating a student object with the information parsed from the file
CurrentStudent student(newRecord.at(0), newRecord.at(1), newRecord.at(2).toInt(), newRecord.at(3).toInt(), newRecord.at(4).toInt(), newRecord.at(5).toUInt());
currentStudents.push_back(student);
}
catch (const std::out_of_range& e)
{
qDebug() << "OUT OF RANGE ERROR: " << e.what();
}
lineindex++;
}
如果文件中的记录以任何奇怪的方式格式化,例如(,,,,,,)或没有6个逗号来分隔数据,它将不正确地将记录加载到表中然后导致超出范围最终错误。如何让程序跳过有问题的行并移到下一行?
答案 0 :(得分:0)
您可以添加验证测试:
while (!input.atEnd())
{
// ...
for (int i = 0; i < lineToken.size(); i++) {
// load newRecord...
}
// validate..
if (newRecord.size() != 6)
{
// print warning here ?
// skip
continue;
}
if (newRecord.at(0) == "") // for example...
{
// print warning here ?
// skip
continue;
}
// more validation ?
// add record
CurrentStudent student(newRecord.at(0), newRecord.at(1), newRecord.at(2).toInt(), newRecord.at(3).toInt(), newRecord.at(4).toInt(), newRecord.at(5).toUInt());
currentStudents.push_back(student);
} // end loop