目标是让程序从文本文件中读取,用# 符号解析它,然后打印出商品和价格。它处于循环中,因此需要重复,因为有 3 个项目。它还需要计算项目的数量(基于行)并将所有价格加在一起以获得总价格。它需要解析的文本文件如下所示:
锤子#9.95 锯#20.15 铲#35.40
我的代码如下:
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
ifstream invoice("invoice2.txt");
string name;
int count = 0;
int totalPrice = 0;
float price = 0.0;
while(invoice.open())
{
getline(file, line);
++count;
for (string line; getline(file, line); )
{
size_t sharp = line.find('#');
if (sharp != string::npos)
{
string name(line, 0, sharp);
line.erase(0, sharp+1);
price = stof(line);
cout << "*** Invoice ***\n";
cout << "----------------------------\n";
cout << name << " $" << price << "\n\n";
cout << "----------------------------\n";
cout << count << " items: " << totalPrice;
}
}
}
return 0;
}
循环需要重复直到文本文件结束,然后它应该中断并打印总价格