float to string

Feb 26, 2009 at 6:51pm
I am working on a project for a class, and I was just wondering if there is a function for converting a float to a string, and vice versa.
Last edited on Feb 26, 2009 at 6:51pm
Feb 26, 2009 at 7:01pm
closed account (z05DSL3A)
Look into stringstream...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>
using namespace std;

int main () {

  float val =3.456;
  stringstream ss (stringstream::in | stringstream::out);

  ss << val;

  string test = ss.str();

  cout << test <<endl;

  return 0;
}
Feb 26, 2009 at 7:07pm
1
2
#include <boost/lexical_cast.hpp>
cout << boost::lexical_cast<string>( 3.14 );


is another alternative that does essentially the same thing as what Grey Wolf wrote.
Feb 26, 2009 at 7:32pm
jsmith, it says that boost/lexical_cast.hpp is nonexistant, but greywolf's option works, but i need something that also converts from string to float
Last edited on Feb 26, 2009 at 7:53pm
Feb 26, 2009 at 7:44pm
closed account (z05DSL3A)
1
2
3
4
5
string test ="445.26";
  ss << test;
  float val; 
  ss >> val;  
  cout << val <<endl;


To use Boost you would have to download and install it. http://www.boost.org/
Feb 26, 2009 at 7:54pm
Well I went with GreyWolf's example, and I finished the project, thanks guys.
Feb 26, 2009 at 10:04pm
Ya, too bad.

 
float f = boost::lexical_cast<float>( "3.14" );


boost works both ways.
Topic archived. No new replies allowed.