Harts
Harts

Reputation: 4103

C++ how to read a file and parse the comma separated value

How to read file, and get the last part of comma separated value, to be used for sum. e.g: I have this file name with this data

2014-12-22.16:31:36,3,3
2014-12-22.16:31:37,3,6
2014-12-22.16:31:38,3,9
2014-12-22.16:31:39,6,15

What I would like to get is actually the number 15 as an integer. so I can do addition with some other number. but any other way is also ok.. that number 15 is essentially, the sum of all 2nd part of comma separated value. I have the reading part

if(IsFileExist(theFileName)) {
    std::ifstream file(theFileName);
    std::string str; 

    while (std::getline(file, str)) {

    }
}

Upvotes: 2

Views: 6085

Answers (2)

David G
David G

Reputation: 96845

Once you have the line, search for the last comma which should be followed by the data to be summed. Use std::stoi() to convert the substring:

#include <iostream> // std::cout
#include <fstream>  // std::ifstream
#include <string>   // std::string, std::getline

int main()
{
    int sum(0);
    for (std::string line; std::getline(file, line); )
    {
        std::string::size_type pos = line.find_last_of(',');
        try
        {
            sum += std::stoi(line.substr(pos+1));
        }
        catch (...)
        {
            std::cerr << "Invalid CSV\n";
            csv.setstate(std::ios_base::failbit);
        }
    }
    std::cout << sum;
}

Upvotes: 2

Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

As my experience you have to use some real library if your CSV includes symbols specially ,. You can consider Boost Tokenizer (http://www.boost.org/doc/libs/1_55_0/libs/tokenizer/). but if your data never includes , just uses string spiting method

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

Upvotes: 2

Related Questions