2011-10-30 3 views
0

Je voudrais convertir une chaîne en float en C++. essaie actuellement d'utiliser atof. Les suggestions sont très appréciées.tokenizer convertir la chaîne en float

ils arrivent comme: 2.22,2.33,2.44,2.55

à la fin, je voudrais le tableau de température pour ressembler à: Temp [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++; 
} 

Répondre

1

Vous pouvez toujours utiliser lexical_cast de boost, ou l'équivalent non-boost:

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

Je voudrais simplement utiliser un 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

Votre approche est très bien, mais attention aux conditions limites:

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; 
} 
Questions connexes