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

Sea*_*ean 3 c++ arrays string floating-point

你将如何转换一个字符串,让我们说: 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};

Rob*_*obᵩ 12

我将使用以下数据结构和算法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";
}
Run Code Online (Sandbox Code Playgroud)

  • 是.添加`using namespace std`可以引入bug.这里有一个问题的正确描述:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c (2认同)
  • @Sean:阅读答案[这里](http://stackoverflow.com/questions/1265039/using-std-namespace)与最多的投票(我建议永远不要使用它). (2认同)