【问题标题】:C++ - Extract string from comma separated float lineC++ - 从逗号分隔的浮点行中提取字符串
【发布时间】:2018-05-30 01:44:35
【问题描述】:

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

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

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

提示:

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

【问题讨论】:

  • 不,我只需要字符串,但我是 c++ 新手,我不知道如何使用 c++(这是一项要求)
  • 您似乎想获取最后一个, 之后的子字符串。一个正则表达式可以是[^,]+$
  • @GregórioGranadoMagalhães std::regex 解析它似乎有点矫枉过正。
  • 其实我不知道更好的方法,只是一个建议。

标签: c++ regex string istringstream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    一个简单的解决方案是首先使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      相关资源
      最近更新 更多