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);
}
现在,我只得到第一行的名称和价格。
如何读取整行存储文件中所有行的所有三个值的行?
价格后,您必须处理逗号:
char comma;
ss >> name >> price >> comma >> amount;
只是为了澄清一下:名称是用第一个逗号读取的。然后,流读取一个double-查找逗号并在此处停止。然后,您请求读取一个int,但它得到的只是...一个逗号。您需要摆脱它才能继续。
更新:
#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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句