C++从文本文件中读取、解析和添加价格
C++ reading from text file, parsing and adding prices
目标是让程序从文本文件中读取,通过#符号解析它,然后打印出项目和价格。它处于循环中,因此需要重复,因为有 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.
相关文章:
- 从文本文件在组合框中添加项目
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
- 如何从 c++ winrt UWP 应用中的代码将文本添加到富文本块
- c++ 添加具有写入文件错误的文本变量
- 在 MFC 组合框中设置文本,而不将其添加到列表中
- 将时间戳添加到文本文件中的空行中
- 将文本添加到鼠标位置时,请单击“给出分割故障”
- 如何在C++的文本变量中添加变量值
- 使用FreeImage向图像添加文本
- 在OpenCV图像中添加文本标签
- 在每行的开头和结尾添加文本
- CMFCPropertyGridCtrl添加文本
- Qt 5.2 -如何在UI中添加文本链接
- 添加文本在GraphicsView在Qt
- 模态对话框继续添加文本
- 在c++中向Win32编辑框添加文本
- 在分配的内存中添加文本
- 向QListWidget的现有项添加文本
- 可以在FileCommonDialog上添加文本框