如何从 CSV 文件中获取数据,并将数据解析为两个逗号之间的 INT?

Posted

技术标签:

【中文标题】如何从 CSV 文件中获取数据,并将数据解析为两个逗号之间的 INT?【英文标题】:How do I take data from a CSV file, and parse the data into an INT between two commas? 【发布时间】:2017-07-31 23:10:44 【问题描述】:

首先,很抱歉这个问题可能不具体,因为这是我第一次问 *** 的问题。

我会开始做生意,我正在做一个项目,它读取一个文件(特别是 CSV),然后将某些数据从那里保存到一个 Int 中,我稍后会搞砸。

基本上,我的代码目前如下:

            if (!infile) 
            cout << "You entered something that cannot be opened, please try again." << endl;
            Continue = true;
        
        else 
            while (infile.good()) 
                getline(infile, value, ','); // read a string until next comma
                cout << string(value, 1, value.length() - 2); // display value removing the first and the last character from it
            
            Continue = false;
        
    

到目前为止,这会读取数据并输出如下所示的行:

    2014-01-03,"2014","01","03","†","-12.8","","-31.0","","-21.9","","39.9","","0.0","","","M","","M","0.0","","","","","","<31",""
2014-01-04,"2014","01","04","†","-2.3","","-12.8","","-7.6","","25.6","","0.0","","","M","","M","2.9","","40","","18","","39",""
2014-01-05,"2014","01","05","†","-2.1","","-4.1","","-3.1","","21.1","","0.0","","","M","","M","16.2","","52","","8","","32",""

我需要的信息在第 5 个和第 6 个逗号之间(它代表一天的平均温度),我需要将这两个逗号之间的信息放入某种 int 中。

同样,第 3 和第 4 个逗号之间是天,稍后我需要用它来计算每个月的平均温度,所以我也需要计算出来。

有谁知道这样做的正确方法?不幸的是,我对字符串解析的了解还不够。

【问题讨论】:

请先搜索再进行。通过在互联网上搜索“*** c++ 读取文件逗号分隔”可以找到大量类似的问题 【参考方案1】:

首先,第 5 和第 6 个逗号之间的值是浮点数 - 您应该将其转换为 floatdouble

那么,

如果两者都

你总是有一个“。”作为浮点数中的分隔符 您可以接受 C++17 或更高版本的语言 使用 std::from_chars (https://en.cppreference.com/w/cpp/utility/from_chars)

如果不是,请考虑以下几点:

对于有符号整数 - std::stoi/std::stol/std::stoll (https://en.cppreference.com/w/cpp/string/basic_string/stol) 和 std::strtol/std::strtoll (https://en.cppreference.com/w/cpp/string/byte/strtol) 对于无符号整数 - std::stoul/std::stoul (https://en.cppreference.com/w/cpp/string/basic_string/stoul) 和 std::strtoul/std::strtoull (https://en.cppreference.com/w/cpp/string/byte/strtoul) 对于浮点数 - std::stof/std::stod/std::stold (https://en.cppreference.com/w/cpp/string/basic_string/stof), std::strtof/std::strtod/std::strtold (https://en.cppreference.com/w/cpp/string/byte/strtof) 和宽字符串 std ::wcstof/std::wcstod/std::wcstold (https://en.cppreference.com/w/cpp/string/wide/wcstof)

如果您的编译器不支持上述功能,您唯一的选择是 atoi/atol (https://en.cppreference.com/w/cpp/string/byte/atoi) 和 atof (https://en.cppreference.com/w/cpp/string/byte/atof) 和 sscanf (https://en.cppreference.com/w/cpp/io/c/fscanf)。

【讨论】:

以上是关于如何从 CSV 文件中获取数据,并将数据解析为两个逗号之间的 INT?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Python 获取 PickleType 数据并转换为文件夹中的 csv 文件

BASH - 如何从 CSV 文件中的列中提取数据并将其放入数组中?

在 android 中获取和解析 CSV 文件

如何从 CSV 文件导入数据并将其存储在变量中?

如何从android下载firebase数据库作为CSV文件

将数据从 Web 托管的 CSV 加载到 Oracle 中?