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 read in each line creating new object line while (getline(infile, line, '\n')) { istringstream ss(line); ss >> name >> price >> amount; products newproduct(name, price, amount); item.push_back(newproduct); }
right getting name , price of first line.
how can read in entire line storing 3 values lines in file?
you've got handle comma after price:
char comma; ss >> name >> price >> comma >> amount;
just clarify: name read first comma. stream reads double - finds comma , stops here. request read int got is... comma. need rid of 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
Post a Comment