String & ASCII code

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I've just started programming with C++, and I'm looking for a way (function)
to convert numbers (int,float or double) into ASCII.

Thanks
 
Nigel said:
Hello,

I've just started programming with C++, and I'm looking for a way
(function) to convert numbers (int,float or double) into ASCII.

The old 'C' way would be to use sprintf. The following simple example
illustrates the use, but it full of potential problems (sprintf is one of
the biggest contributors to buffer overrun bugs).

<code>
#include <stdio.h>

void f(int i)
{
char sz[20];
sprintf(sz,"%d",i);
}
</code>

The modern 'C++' way would be to use ostringstream. The following sample
illustrates usage.

<code>
#include <sstream>
#include <string>

using namespace std;

string to_string(int i)
{
ostringstream os;
os << i;
return os.str();
}
</code>

I'd suggest looking up ostringstream in your favorite C++ book and learn
more about it.

-cd
 
Greetings,

I'm a self taught C++ user, and I can highly recommend the QUE series of
reference books at your local bookstore. Get both C and C++ books. I remember
being frustrated trying to look in C++ help documentation for lots of
questions like yours, that were really C issues. Since C++ is built on C,
too often the help documentation presumes the reader has a working knowledge
of C, and focuses only on C++ features like classes and objects.

I've also gotten some SAMS books, but I like the QUE much better. Stay away
from the "XXX for Dummies" books, the discussion is too superficial in my
opinion.

Enjoy,

Mike
 
Back
Top