首页 > 解决方案 > 我的程序没有读取所有 .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);

}

标签: c++

解决方案


数字中的逗号将使其无法解析。您可以逐行读取文件,过滤掉逗号并用于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....
    }
}

推荐阅读