3

Possible Duplicate:
Convert double to string C++?

I searched in the page but i haven't found the solution.

I have a method to convert from int to string. But now i need to convert from float/double to string. Because i want to write some data in a file.

Anyone could help me ??

Thanks in advance.

Community
  • 1
  • 1
Jorge Vega Sánchez
  • 7,430
  • 14
  • 55
  • 77

5 Answers5

8

http://www.daniweb.com/software-development/cpp/threads/146718

#include <sstream>
std::string Convert (float number){
    std::ostringstream buff;
    buff<<number;
    return buff.str();   
}
einverne
  • 6,454
  • 6
  • 45
  • 91
John K.
  • 5,426
  • 1
  • 21
  • 20
5

You could use sprintf.

You could use stringstream with << operator.

See also Convert double to string C++?, How do I convert a double into a string in C++?, Convert double to string using boost::lexical_cast in C++?, Converting Double to String in C++, etc.

Community
  • 1
  • 1
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
4

Can you not use the standard (C) function sprintf/fprintf etc?

Liv
  • 6,006
  • 1
  • 22
  • 29
  • No i need a conversion before writing the file. – Jorge Vega Sánchez Apr 26 '11 at 21:06
  • sprintf allows you to "convert" (format really) into a string (char *) -- which you then can write to file or do with it as you please really. – Liv Apr 27 '11 at 10:54
  • Note that windows until recently did not support the same snprintf commands that linux does, and they don't work in the same way. This caused portability issues with code. As of the latest Visual Studio Microsoft's implementation of snprintf is standards compliant. – Owl Sep 08 '16 at 08:03
3

This can help you : Convert double to string C++?

Community
  • 1
  • 1
Drahakar
  • 5,986
  • 6
  • 43
  • 58
2

Is your file written using IOStreams? If so, just do this:

stream << number;

If not, and you really need a string, you can use an ostringstream for this. Boost's lexical_cast wraps the string streams in an easy-to-use fashion.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435