C++ C++;从文本文件读取、解析和添加价格
目标是让程序从文本文件中读取,用#符号对其进行解析,然后打印出项目和价格。它处于循环中,因此需要重复,因为有3项。它还需要计算项目的数量(基于行),并将所有价格相加,形成总价。它需要解析的文本文件如下所示: hammer#9.95 saw#20.15 shovel#35.40 锤子#9.95 锯20.15 铲子#35.40 我的代码如下:C++ C++;从文本文件读取、解析和添加价格,c++,file,parsing,C++,File,Parsing,目标是让程序从文本文件中读取,用#符号对其进行解析,然后打印出项目和价格。它处于循环中,因此需要重复,因为有3项。它还需要计算项目的数量(基于行),并将所有价格相加,形成总价。它需要解析的文本文件如下所示: hammer#9.95 saw#20.15 shovel#35.40 锤子#9.95 锯20.15 铲子#35.40 我的代码如下: #include <string> #include <fstream> #include <iostream> #in
#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream发票(“invoice2.txt”);
字符串名;
整数计数=0;
int totalPrice=0;
浮动价格=0.0;
while(invoice.open())
{
getline(文件,行);
++计数;
for(字符串行;getline(文件,行);)
{
size_t sharp=line.find(“#”);
if(sharp!=字符串::npos)
{
字符串名称(行,0,夏普);
行。擦除(0,夏普+1);
价格=stof(行);
首先,为什么要使用while
循环?您不需要这样做
第二,在内部循环前面加上初始的getline
,跳过第一行
第三,您从不向totalPrice
添加任何内容。您每次都在内部循环中打印。它不应该在循环后打印吗
因此,请改为以下伪代码:
if (invoice.isopen())
{
print_header();
while (getline())
{
parse_line();
print_current_item();
totalPrice += itemPrice;
}
print_footer_with_total(totalPrice);
invoice.close();
}
首先,为什么要使用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的delimiter参数呢
for (string str; getline(file, str, '#'); ) {
double price;
file >> price >> ws;
totalPrice += price;
// handle input...
}
// print total etc.
为什么不使用getline的delimiter参数呢
for (string str; getline(file, str, '#'); ) {
double price;
file >> price >> ws;
totalPrice += price;
// handle input...
}
// print total etc.
问题是什么?问题是什么?