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

3
你如何将一个字符串转换为浮点数数组?比如说: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};

我进行了一些搜索,似乎被引导到了strtok函数,但其他搜索似乎在说你需要一个更定制化的函数。如果这里没有人回答,也许你可以在Google上找到更好的答案。 - TecBrat
是的,那是我的想法。我打算尝试使用strtok()将其分解为单个字符串,然后使用atof()将字符串转换为浮点数(请记住我是一名初学者程序员),但我在分解字符串时遇到了问题。 - Sean
1个回答

15

我会使用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";
}

你为什么没有使用 using namespace std 呢? - Sean
2
是的。添加 using namespace std 可能会引入错误。这里有一个关于这个问题的不错描述:https://dev59.com/D3M_5IYBdhLWcg3wQQ3w - Robᵩ
2
@Sean:在这里阅读得票最高的答案(我建议永远不要使用它)。 - Jesse Good

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接