如何使用分隔符获取所有第二个字段的总和
How to get the total sum of all the 2nd fields with delimiter?
我想编写代码来获取整个文本文件的第二个字段,并将所有第二个字段的总值相加,这些字段的数字可能具有小数位。例如输入文件
electricity:200:20jan2010
utilities:200:20jan2010
原型:
#include <iostream>
#include <fstream>
int main(){
while(getline(file, line)){
stringstream linestream(line);
string data1;
double data2;
string data3;
getline(linestream, data1, ':');
getline(linestream, data2, ':');
/*how should i write the code to get the sum of 2nd field only*/
}
}
这将有助于您的问题...此代码生成所有正值和负值,如果您希望它是特定的,请删除 totalPositive 或 totalNegative 以满足您的要求
std::ifstream file("Expense.txt");
std::string line;
double totalNegative = 0;
double totalPositive = 0;
while(std::getline(file, line))
{
std::stringstream linestream(line);
std::string data1;
double data2;
std::string data3;
getline(linestream, data1, ':');
linestream >> data2;
if (data2 > 0)
totalPositive += data2;
else
totalNegative =- data2;
下面是一个示例。 效率不是很高,但你可以明白这个想法。
while(getline(file, line)){
size_t pos;
while ((pos=line.find(":"))!=string::npos) line.replace(pos,1," ");
istringstream linestream(line);
string data1;
double data2;
linestream >> data1 >> data2;
}
另外,这里有一个简单的字符串分词器,它可以处理这个问题以及更多:
#include <string>
#include <vector>
class string_tokenizer
{
typedef std::string str;
typedef std::vector<str> seq;
seq m_Tokens;
unsigned m_Current;
public:
string_tokenizer(const str& s, const str& delim=" t")
: m_Current(0)
{
int p=-1;
int len=s.length();
while (true)
{
p=s.find_first_not_of(delim,p+1);
if (p<0) break;
int e=s.find_first_of(delim,p+1);
if (e<0) e=len;
m_Tokens.push_back(s.substr(p,e-p));
p=e;
}
}
typedef typename seq::const_iterator const_iterator;
const_iterator begin() const { return m_Tokens.begin(); }
const_iterator end() const { return m_Tokens.end(); }
unsigned size() const { return m_Tokens.size(); }
bool has_more_tokens() const { return m_Current<m_Tokens.size(); }
str get_next_token()
{
if (m_Current<m_Tokens.size()) return m_Tokens[m_Current++];
return str("");
}
};
相关文章:
- 使用 Boost::Hana 中的 BOOST_HANA_DEFINE_STRUCT 定义具有 40 个以上字段的结构
- 如何从对象/类中找到第一个字段?
- C++创建一个链表,每个节点有超过 2 个字段
- 为什么字段中的第二个变量没有更改
- 可以将模板字段参考模板参数作为第一个模板参数传递
- 如何从具有多个对象/字段的类中调用方法函数
- 为什么在使用 select() 时连接到带有第二个套接字的服务器"break"第一次连接?
- 两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?
- 定义静态类字段时多个已定义符号的链接器错误
- 将两个重复字段与C++ API 进行比较
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- C 中的多个相邻位字段
- 设计具有变体字段的文本类型类,其中可以存储一个或三个对象
- 在特定字段中关键字搜索后,从文本文件中提取多个记录
- C 列表一次由多个字段排序
- 如何创建具有4个字段和每个字段9个字符长度的矢量对象
- 类的第二个实现文件中静态字段的C++外部
- Lua:加载第二个字符串后无法获取字段;
- 如何使用分隔符获取所有第二个字段的总和
- 无法使用end()获取映射的第二个字段