如何将字符串转换为浮点数组? [英] 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;
//如果可能的话,总是比较喜欢std :: vector到裸集合
std :: vector< float> v;
//建立一个持有输入字符串的istream
std :: istringstream iss(Numbers);
//迭代istream,使用>>抓取浮点数
// push_back将其存储在向量中
std :: copy(std :: istream_iterator< float>(iss),
std :: istream_iterator< float>() ,
std :: back_inserter(v));
//将结果标准化为
std :: copy(v.begin(),v.end(),
std :: ostream_iterator< float>(std :: cout,,));
std :: cout<< \\\
;
}
How would you convert a string, lets say:
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};
?
解决方案
I would use data structures and algorithms from 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";
}
这篇关于如何将字符串转换为浮点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文