C ++ - 从逗号分隔的浮点行

时间:2017-12-15 20:13:00

标签: c++ regex string istringstream

我有一个文件,其格式如下:0.123,0.432,0.123,ABC

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

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

提示:

  • 由于已知每行中的元素数量不是问题
  • 此外我并不特别需要使用这种结构,我只是使用它,因为它是迄今为止我发现的最好的结构。
  • 我想要的就是最后有一个带浮动元素的向量和一个带有最后一个字段的字符串。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

RegEx对此任务来说太过分了,substr会在您要求string向量时返回float。我认为你需要的是使用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