How do I convert a std::string to a float?

Started by
7 comments, last by Deranged 18 years, 11 months ago
Jake
Advertisement
std::stringstream

#include <sstream>float ToFloat(const std::string s){  float n;  std::stringstream ss(s);  ss >> n;  return n;}
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
thx man
Or, if you have boost:

std::string string_num = "3.141";
float float_num = boost::lexical_cast<float>(string_num);

Jim.
C-style:
std::string val = "12.5";float fval = atof( val.c_str() );
sprintf, snprintf et. al.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
I'm not sure how sprintf would help. sscanf, maybe.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
what i use:float stof(std::string in){    //revision from http://www.jbox.dk/sanos/source/lib/strtod.c.html    //Since mine is just a revision(in my opinion better) of the atof shown there, posting the whole thing would be useless}
^^Tis me, if it logs me out one more time :(^^

This topic is closed to new replies.

Advertisement