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

问题描述 投票:-4回答:2

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

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

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

提示:

  • 由于每行中的元素数量已知,因此不存在问题
  • 我也不特别需要使用这种结构,我只是使用它,因为它是迄今为止我发现的最好的结果。
  • 我想要的最终是一个带有float元素的向量和一个带有最后一个字段的字符串。
c++ regex string istringstream
2个回答
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();
}

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
© www.soinside.com 2019 - 2024. All rights reserved.