简体   繁体   中英

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. eg: 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)) {

    }
}

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';
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM