c++ - 如何将字符串转换为 float 数组?

标签 c++ arrays string floating-point

你会如何转换一个字符串,比方说: string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";转换成float数组,如: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";
}

关于c++ - 如何将字符串转换为 float 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986091/

相关文章:

javascript - 如何不可变地插入已排序的数组?

java - 二维数组旋转

java - 在Java中获取Map中键的值

string - Rebol cd 不需要%?

c++ - 使用表达式-SFINAE 的函数模板的类定义外

c++ - 密码策略 Windows API

c - 在数字数组中输入一个字母

sql - Oracle中将字符串拆分为多行

c++ - 删除不完整类型在 C++ 中不是错误时,是否存在真实案例?

c++ - 如何将 C++ Wii devkitpro 连接到互联网?