#include<iostream>
#include<strstream>
#include<string>
using namespace std;
template <class T> string convert2String (T value) {
ostrstream outs;
outs << value << ends;
return ( outs.str() );
}
int main(int argc, char *argv[]) {
string x1 = convert2String ( (double) 3.414 );
string x2 = convert2String ( (float) 1.23e33 );
string x3 = convert2String ( (int)25 );
cout << x1 << " " << x2 << " " << x3 << endl;
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#define NUM_OF_DIGITS 28
int main(int argc, char* argv[]) {
double value=(sin(45));
long long ival = 0x123456781234578LL;
char buf[NUM_OF_DIGITS];
sprintf(buf,"%.*g",NUM_OF_DIGITS,value);
std::cout << buf << std::endl;
// Same as above but let's only show 5 digits
sprintf(buf,"%.*g",5,value);
std::cout << buf << std::endl;
// Long Long to string conversion
sprintf(buf,"%llx", ival);
std::cout << buf << std::endl;
return 0;
}
don't return strings. you might overload the stack! pass strings (and vectors and queues and other such encapsulated data structures) by reference.Here are two methods:
Example one. Use overloading method to convert
Code:#include<iostream> #include<strstream> #include<string> using namespace std; template <class T> string convert2String (T value) { ostrstream outs; outs << value << ends; return ( outs.str() ); } int main(int argc, char *argv[]) { string x1 = convert2String ( (double) 3.414 ); string x2 = convert2String ( (float) 1.23e33 ); string x3 = convert2String ( (int)25 ); cout << x1 << " " << x2 << " " << x3 << endl; return 0; }
look up the function 'itoa"
Look it up on MSDN. should give you a good start.
I LOVE C !! (embedded world ... it's clean, fast, and if you're careful, it's perfectly safe)It is really amazing how many C programmers there still are today. I've been using the itoa function since 1982. It's hard to believe that these things haven't been replaced yet.
I LOVE C !! (embedded world ... it's clean, fast, and if you're careful, it's perfectly safe)
I LOVE THAT about POSIX ... I count 7 different platforms from full sized rigs to small hand held devices to small pocket sized devices ... all running the same code...And if you take a little care, it compiles and runs on a multitude of platforms
without having to adjust it
hehe -- it depends on the platformThe only bad thing about using C for cross-platform development is that you need to use specific ANSI C/C++ and do not use any specialized libraries. Because of this, Java is typically the better cross-platform development environment.