2011-10-30 23 views
0

我想将字符串转换为C++中的浮点数。目前正试图使用​​atof。任何建议,非常感谢。tokenizer将字符串转换为浮点数

他们来了在为:在端 2.22,2.33,2.44,2.55

,我想临时阵列看起来像: 温度[4] = {2.22,2.33,2.44, 2.55}

getline (myfile,line); 
t_tokenizer tok(line, sep); 
float temp[4]; 
int counter = 0; 

for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg) 
{ 
    temp[counter] = std::atof(* beg); 
    counter++; 
} 

回答

1

您可以随时使用升压转换器的lexical_cast,或者非升压相当于:

string strarr[] = {"1.1", "2.2", "3.3", "4.4"}; 
vector<string> strvec(strarr, end(strarr)); 

vector<float> floatvec; 

for (auto i = strvec.begin(); i != strvec.end(); ++i) { 
    stringstream s(*i); 
    float tmp; 
    s >> tmp; 
    floatvec.push_back(tmp); 
} 

for (auto i = floatvec.begin(); i != floatvec.end(); ++i) 
    cout << *i << endl; 
2

我会简单地用一个stringstream

#include <sstream> 

template <class T> 
bool fromString(T &t, const std::string &s, 
       std::ios_base& (*f)(std::ios_base&) = std::dec)) { 
    std::istringstream iss(s); 
    return !(iss >> f >> t).fail(); 
} 
0

你的做法是好的,但要注意边界条件:

getline (myfile,line); 
t_tokenizer tok(line, sep); 
float temp[4]; 
int counter = 0; 

for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end() && counter < 4; ++beg) 
{ 
    temp[counter] = std::atof(* beg); 
    ++counter; 
} 
相关问题