加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何将字符串转换为浮点数组?

发布时间:2020-12-16 10:21:42 所属栏目:百科 来源:网络整理
导读:你会如何转换字符串,让我们说: string Numbers =“0.3 5.7 9.8 6.2 0.54 6.3”;进入浮点数组,例如:float Numbers [6] = {0.3,5.7,9.8,6.2,0.54,6.3} ;? 解决方法 我会使用std :::的数据结构和算法 #include string#include vector#include algorithm#inclu
你会如何转换字符串,让我们说:
string Numbers =“0.3 5.7 9.8 6.2 0.54 6.3”;进入浮点数组,例如:float Numbers [6] = {0.3,5.7,9.8,6.2,0.54,6.3} ;?

解决方法

我会使用std :::的数据结构和算法

#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cassert>
#include <sstream>

int main () {
  std::string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";

  // If possible,always prefer std::vector to naked array
  std::vector<float> v;

  // Build an istream that holds the input string
  std::istringstream iss(Numbers);

  // Iterate over the istream,using >> to grab floats
  // and push_back to store them in the vector
  std::copy(std::istream_iterator<float>(iss),std::istream_iterator<float>(),std::back_inserter(v));

  // Put the result on standard out
  std::copy(v.begin(),v.end(),std::ostream_iterator<float>(std::cout,","));
  std::cout << "n";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读