在c++中提取txt文件时出现问题


#include <string>
using namespace std;

int main() 
{
string product_name;
float price;
ifstream file("shopping.txt");

while(file >> product_name >> price) {
cout << product_name << ": " << price << " euros" << endl;
}
if (!file.is_open()) {
cout << "Failed to open the file!" << endl;
exit(-1);
}
}

我目前正在学习c++,特别是OPP,遇到了一个问题,要求从文本文件中提取信息并将其打印在屏幕上

这里的txt文件名"shopping.txt">

pears       1.23
ham pizza   1.95
salad       0.80
lemonade    1.67
newspaper   2.00
beef        3.52
potatoes    1.52
milk        0.80

当我使用字符串变量表示价格时,它工作得很好,但因为我想用于计算,例如总费用,我将其更改为float类型,但程序只返回txt文件的第一行并停止

我希望这将打印出整个列表,其中var价格为浮点数,以便进一步计算

问题是file >> product_name读取单个但是在你的文件的第二行你有ham pizza,这是两个单词。这将导致读取失败,因为您的代码将尝试将pizza作为浮点值读取。

有很多方法可以解决这个问题,但老实说,最简单的方法就是把文件改成
ham-pizza   1.95

阅读完产品名称后,可以将破折号改为空格。

最新更新