我的程序未读取所有.txt文件

时间:2018-11-07 21:52:00

标签: c++

我正在尝试将.txt文件读入对象,然后将其存储在链接列表中,但它只会读入文件的一半。

enter image description here

这就是我要尝试阅读的内容,但只能读到道奇恶魔。

 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);

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可能要使用std::getline来阅读文本行,然后使用std::istringstream来分析文本:

std::string  record;
while (std::getline(CarsFile, record))
{
    std::istringstream car_stream(record);
    std::string make;
    std::getline(car_stream, make, ',');
    //...
}
相关问题