简体   繁体   English

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

[英]How do you convert a string into an array of floats?

How would you convert a string, lets say: string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3"; 你会如何转换一个字符串,比如说: string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3"; into a float array, such as: float Numbers[6] = {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}; ?

I would use data structures and algorithms from std:: : 我会使用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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM