如何使用分隔符获取所有第二个字段的总和

How to get the total sum of all the 2nd fields with delimiter?

本文关键字:字段 第二个 何使用 分隔符 获取      更新时间:2023-10-16

我想编写代码来获取整个文本文件的第二个字段,并将所有第二个字段的总值相加,这些字段的数字可能具有小数位。例如输入文件

 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("");
  }
};