C - 从逗号分隔的浮点线提取字符串

C++ - Extract string from comma separated float line

本文关键字:提取 字符串 分隔      更新时间:2023-10-16

我有一个带有以下模式的文件: 0.123,0.432,0.123,ABC

我已经成功地将浮点数检索到一个数组中,但是我现在需要找到一种获取最后一个字符串的方法。我的代码如下:

    vector<float> test;
    for (float v = 0; test_ss >> v; ) {
        test.push_back(v);
        test_ss.ignore();
    }

提示:

  • 作为每行元素的数量,它不是一个问题
  • 我也不需要特别使用这种结构,我只是在使用它,因为它是我到目前为止发现的最好的。
  • 我想要的是,最终要拥有一个带有浮点元素的向量和一个带有最后一个字段的字符串。

一个简单的解决方案是首先使用 std::replace( test_ss.begin(), test_ss.end(), ',', ' ');替换字符串,然后使用for loop:

vector<float> test;
for (float v = 0; test_ss >> v; ) {
    test.push_back(v);
    test_ss.ignore();
}

RegEx将是此任务的过度杀伤,而 substr将返回 string,而您询问 float vector。我认为您需要的是使用ifstream并将逗号阅读到虚拟char

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
int main() 
{
    std::ifstream ifs("file.txt");
    std::vector<float> v(3);
    std::string s;
    char comma; // dummy
    if (ifs >> v[0] >> comma >> v[1] >> comma >> v[2] >> comma >> s)
    {
        for (auto i : v)
            std::cout << i << " -> ";
        std::cout << s << std::endl;
    }
    return 0;
}

打印:

0.123 -> 0.432 -> 0.123 -> ABC