簡體   English   中英

如何將字符串轉換為浮點數組?

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

你會如何轉換一個字符串,比如說: 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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM