【问题标题】:Reading in a list of csv floats with a prefix in C++在 C++ 中读取带有前缀的 csv 浮点数列表
【发布时间】:2020-01-22 22:08:36
【问题描述】:

我正在尝试从文件中读取格式如下例的浮点数列表并读取到向量中,然后再次将它们打印出来。有没有办法修改流或迭代器以删除表示浮动的“f”并以最小的更改正确解析数据?

1.5f, 2.0f, 4.0f, 1.0f, 1.0f, 2.0f, 4.0f, 2.0f, 1.0f, 0.0f, 0.0f, 1.0f, 9.0f

代码在这里

std::ifstream infile("matrices.txt");
std::string s;
std::vector<float> A;

std::getline(infile,s,'\n');
std::stringstream mss(s);
std::copy(std::istream_iterator<float>( mss ), std::istream_iterator<float>(),std::back_inserter(A));    
std::copy(A.begin(), A.end(), std::ostream_iterator<float>(std::cout, ", "));

【问题讨论】:

    标签: file c++11 parsing


    【解决方案1】:

    您可以请求字符串流在每次提取浮点数时忽略 2 个字符。

      float x{};
      while (!mss.eof())
      {
          mss >> x;
          mss.ignore(2);
          vfloats.push_back(x);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2022-11-23
      • 1970-01-01
      相关资源
      最近更新 更多