Lexicon
Lexicon

Reputation: 2627

tokenizer convert string to float

I'd like to convert a string to a float in C++. currently trying to use atof. Any suggestions are much appreciated.

they are coming in as: 2.22,2.33,2.44,2.55

at the end, I'd like the temp array to look like: 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++;
}

Upvotes: 0

Views: 1271

Answers (3)

CapelliC
CapelliC

Reputation: 60034

Your approach is fine, but beware to boundary conditions:

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

Upvotes: 0

Morten Kristensen
Morten Kristensen

Reputation: 7623

I would simply use a 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();
}

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75150

You can always use boost's lexical_cast, or the non-boost equivalent:

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;

Upvotes: 1

Related Questions