我有一个看起来像这样的代码
#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
第一个始终是客户的名称,其后是他购买的产品及其值(value)。
例如,彼得以8000的价格购买了一杯,但大卫以两种不同的价格购买了2本书。
这就是我的问题所在,因为在David的生产线上,该程序仅返回第一本书的值(value),而不是该生产线的总和,而且我想知道这家商店赚了多少利润,因此我需要计算大卫帐单的总和。
最佳答案
令file
为
std::ifstream file;
现在,以下应该工作,结果包含在
accu
中:int accu = 0;
for (std::string line; std::getline(file,line);)
{
// replace non-spaces and non-digits by nothing
// thus only spaces and digits are left
std::string numbers = std::regex_replace(line, std::regex(R"([^\\d])"), "");
std::stringstream ss(numbers);
for (int price; ss >> price;)
{
accu += price;
}
}
首先,我们逐行读取文件。
对于每一行,我们去除非数字字符,但不去除空格,因为我们需要它们来分隔数字。使用
std::stringstream
我们提取给定的数字。另外,我利用了
#include <sstream>
#include <string>
#include <regex>
版本
c++11
应该足够。注意:只要名称或单词包含其他数字或数字,结果显然是不正确的。可以扩展正则表达式以消除数字内的数字以部分解决此问题。否则,需要有关文件结构的更多信息。