C++如何读取文件并解析逗号分隔值

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

本文关键字:分隔 文件 何读取 读取 C++      更新时间:2023-10-16

如何读取文件,并获取逗号分隔值的最后一部分,用于求和。 例如:我有这个文件名和这个数据

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

我想要得到的实际上是数字 15 作为整数。 所以我可以用其他数字做加法。 但任何其他方式也可以.. 数字 15 本质上是逗号分隔值的所有第 2 部分的总和。我有阅读部分

if(IsFileExist(theFileName)) {
    std::ifstream file(theFileName);
    std::string str; 
    while (std::getline(file, str)) {
    }
}

获得该行后,搜索最后一个逗号,该逗号后应跟要求和的数据。使用 std::stoi() 转换子字符串:

#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 CSVn";
            csv.setstate(std::ios_base::failbit);
        }
    }
    std::cout << sum;
}

根据我的经验,如果您的 CSV 包含特别,符号,您必须使用一些真正的库。您可以考虑使用Boost Tokenizer(http://www.boost.org/doc/libs/1_55_0/libs/tokenizer/(。但是,如果您的数据从未包含,则仅使用字符串吐槽方法

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
    std::cout << token << 'n';
}