C++ 使用stringstream读取不同元素的行
我有一个文件需要读取,看起来像这样:C++ 使用stringstream读取不同元素的行,c++,C++,我有一个文件需要读取,看起来像这样: 1 2.23 Dove Body Wash 3 .50 Bic Pen 11 12.99 Tombstone Pizza 其中,带有产品名称的字段只能有一个单词(洗发水)或任意数量的单词(Big mama’s homestyle牛排薯条)。输入文件也可以有空行,我只需要跳过 所以我现在看到的是这样的(使用getline和stringstream): 此结构: struct CartItem { string itemName; int quantity
1 2.23 Dove Body Wash
3 .50 Bic Pen
11 12.99 Tombstone Pizza
其中,带有产品名称的字段只能有一个单词(洗发水)或任意数量的单词(Big mama’s homestyle牛排薯条)。输入文件也可以有空行,我只需要跳过
所以我现在看到的是这样的(使用getline和stringstream):
此结构:
struct CartItem {
string itemName;
int quantity;
double pricePerItem;
CartItem();
CartItem(string name, int qty,double price);
};
然后是这个代码
while (getline(itemList, inputline)) { //itemlist is my ifstream, inputline is a string declared.
ss.clear();
ss.str(inputline);
ss >> item.quantity >> item.pricePerItem >> item.itemName;
string word;
while (ss >> word)
{
item.itemName += " " + word;
}
if (ss.fail()) {
continue;
}
else
shoppingList.push_back(item);
}
sortItems(shoppingList, sortedList);
printReport(sortedList);
但它不工作(只是崩溃)。如果我用
If(ss>>word)
替换while(ss>>word)
片段,它可以工作,但我只从文件中获取第二个字符串。有人知道我做错了什么吗?你应该提供更多的细节,例如“只是撞车”的意思。然而,我认为你的逻辑有问题。
ss>>当ss
已经没有单词时,while循环中的最终检查将调用word
,因此当while循环退出时,单词将无法提取到word
,设置ss
的失败位。现在,ss.fail()
我猜你以后会依赖于shoppingList
至少有一种商品,这就是崩溃
尝试更改:
while (ss >> word)
{
item.itemName += " " + word;
}
致:
只是一个建议:在删除每件商品的数量和价格后,您可以在stringstream
上使用getline
,以获得剩余的商品名称。非常感谢先生。
while (ss.good())
{
ss >> word;
item.itemName += " " + word;
}