C++从文本文件中读取、解析和添加价格

C++ reading from text file, parsing and adding prices

本文关键字:添加 文本 文件 读取 C++      更新时间:2023-10-16

目标是让程序从文本文件中读取,通过#符号解析它,然后打印出项目和价格。它处于循环中,因此需要重复,因为有 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 << "nn";
            cout << "----------------------------n";
            cout << count << " items:             " << totalPrice;
            }
    }
}
return 0;
}

循环需要重复,直到文本文件结束,然后它应该中断并打印总价

首先,为什么是while循环?你不需要那个。

其次,通过在内部循环之前设置初始getline来跳过第一行。

第三,你永远不会向totalPrice添加任何东西。而且您每次都在内循环内打印。循环不应该打印吗?

因此,请更改为类似于以下伪代码的内容:

if (invoice.isopen())
{
    print_header();
    while (getline())
    {
        parse_line();
        print_current_item();
        totalPrice += itemPrice;
    }
    print_footer_with_total(totalPrice);
    invoice.close();
}

为什么不使用getline的分隔符参数?

for (string str; getline(file, str, '#'); ) {
  double price;
  file >> price >> ws;
  totalPrice += price;
  // handle input...
}
// print total etc.