c++ - 我的程序没有读取所有 .txt 文件
问题描述
我正在尝试将 .txt 文件读入一个对象,然后将其存储在一个链表中,但它只会读取文件的一半。
这就是我要尝试阅读的内容,但它只能读取 Dodge Demon。
while (CarsFile >> make >> model >> price >> year >> horsePower >> torque >> zeroToSixty >> weight >> quarterMile)
{
car.setMake(make);
car.setModel(model);
car.setPrice(price);
car.setYear(year);
car.setHorsePower(horsePower);
car.setTorque(torque);
car.setZeroToSixty(zeroToSixty);
car.setWeight(weight);
car.setQuarterMile(quarterMile);
list.appendNode(car);
}
解决方案
数字中的逗号将使其无法解析。您可以逐行读取文件,过滤掉逗号并用于std::stringstream
解析。
std::string line;
while (std::getline(CarsFile, line)) {
// Remove commas
line.erase(std::remove(line.begin(), line.end(), ','), line.end());
// Use stringstream to parse
std::stringstream ss(line);
if (ss >> make >> model >> price >> year >> horsePower >> torque >> zeroToSixty >> weight >> quarterMile) {
// Add to list....
}
}
推荐阅读
- c - 速记 c if else 语句和循环中断的组合使用导致错误
- angular - 将一个变量传递给另一个变量
- hyperledger-fabric - HYperledger composer v0.19.2 网络启动失败并出现错误 [lscc] executeDeployOrUpgrade -> ERRO 46e 无法获取链码的包?
- c++ - 替代运算符 - 导致内联汇编错误
- c - 处理两个线程,一个在休眠,一个在等待输入
- json - 转换 JSON 时间和日期格式和位置格式
- python - 如何在“ms5837-python”包中查看传感器功能
- angularjs - 如何在角度中设置选定的多选项
- terminology - 专用软件的最佳术语是什么?
- javascript - 不明白 Javascript 在这段代码中是如何工作的(在 Node.js 中使用 Coffeescript、Commander)