float to string

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
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;
}
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.
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
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/
Well I went with GreyWolf's example, and I finished the project, thanks guys.
Ya, too bad.

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


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