【发布时间】:2020-03-22 13:38:38
【问题描述】:
我有一个看起来像这样的代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
struct Bill{
std::string name;
int bill_value;
};
enum Status{abnorm, norm};
bool read(std::ifstream &f, Bill &e, Status &st);
int main()
{
std::ifstream x("inp.txt");
if (x.fail() ) {
std::cout << "Error!\n";
return 1;
}
Bill dx;
Status sx;
int s = 0;
while(read(x,dx,sx)) {
s += dx.bill_value;
}
std::cout << "Today income: " << s << std::endl;
return 0;
}
bool read(std::ifstream &f, Bill &e, Status &st){
std::string line;
getline(f,line);
if (!f.fail() && line!="") {
st = norm;
std::istringstream in(line);
in >> e.name;
std::string product;
int value;
e.bill_value= 0;
while( in >> product >> value) e.bill_value+= value;
}
else st=abnorm;
return norm==st;
}
名为inp.txt 的输入文件如下所示:
Joe tv 1200 mouse 50000
Peter glass 8000
Harry mouse 8200 usb 8000 headphones 98900
David book 500 800 mouspad 900
Liam phone 8000 cooler 3000 headphones 3000
Daniel laptop 700 pot 9000
第一个始终是客户的姓名,然后是他购买的产品及其价值。
例如 Peter 花了 8000 买了一个玻璃杯,但 David 以两个不同的价格买了 2 本书。
这就是我的问题所在,因为在 David 的线路中,程序只返回第一本书的价值,而不是线路的总和,我想知道这家商店赚了多少利润,所以我需要还要计算大卫的账单总额。
【问题讨论】:
-
使用 ifstream.getLine() 读取整行,然后在该行上,用空格分隔,读取字符串变量中的第一个变量,然后运行循环读取字符串变量,然后一个 int 变量并继续循环,直到到达行尾。
-
这里是它的工作原理。您向我们展示了您迄今为止尝试过的代码。这表明您已经做出了一些努力,它可以帮助我们准确了解您卡在哪个部分,因此您将获得更好的帮助。目前听起来你只是在期待我们为你做功课。
-
对我来说,棘手的部分不是阅读,而是弄清楚你所阅读的是价格、物品还是人名。我可以解释一下,但我怎么知道你坚持的是什么?