如何用分隔符得到所有第二个字段的总和?

时间:2015-01-25 10:11:32

标签: c++

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

 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*/
    }
}

2 个答案:

答案 0 :(得分:1)

这是一个例子。效率不是很高,但你可以得到这个想法。

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

答案 1 :(得分:1)

这将有助于您的问题...此代码会生成所有正值和负值,如果您希望它具体,请删除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;