Alex Gessinger Alex Gessinger - 27 days ago 6
C++ Question

C++ Read in data types string, int double from a file. Put each line of data into a vector of objects

data file:

candy, 1.99, 26
chips, 2.55, 22

//my attempt to read in each line creating a new object for the line

while (getline(inFile, line, '\n')) {

istringstream ss(line);
ss >> name >> price >> amount;

products newProduct(name, price, amount);
item.push_back(newProduct);
}


Right now I am only getting the name and price of only the first line.

How can I read in the entire line storing all three values for all lines in the file?

Answer

You've got to handle comma after price:

char comma;
ss >> name >> price >> comma >> amount;

Just to clarify: the name is read with the first comma. Then the stream reads a double - finds a comma and stops here. Then you request to read an int but all it got is... a comma. You need to get rid of it to proceed.

Update:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::istringstream file("xxx, 23.0, 11\nyyy, 99.3, 100");
    while (!file.eof()) {
        std::string line;
        std::getline(file, line);
        std::istringstream line_stream(line);

        std::string name;
        double price;
        char comma;
        int amount;
        line_stream >> name >> price >> comma >> amount;
        std::cout << "name: " << name << std::endl;
        std::cout << "price: " << price << std::endl;
        std::cout << "amount: " << amount << std::endl;
        std::cout << "===================" << std::endl;
    }
}
Comments