Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

changing an int to string?? 2

Status
Not open for further replies.

evosix

Programmer
Apr 27, 2003
9
0
0
AU
Hi, me again,

i know of atoi, but is there a reverse of it??

I want to change an int into a string so i can strcat it to another string.

char s1[20]; (eg: "WOW ")
int x = 100;
//something changes 100 to a string here
strcat(s1, x);

//result should be "WOW 100"

Thanks again,

-evosix-
 
Ive tried using:

sprintf(s1, "%f", x);

but in this case, x would have to be a float, and ruins my output:

"WOW 100.000000"

Any suggestions??
Thanks all,

-evosix-
 
Try [tt]sprintf(s1, "%d", x);[/tt] since %d means int.

//Daniel
 
hehe thanks Daniel.

silly me, i thought the f in sprintf meant it had to be a float!! LOL

(Y)
 
In C++, you could also use stringstream

stringstream s;
float f;
int i;

s << f << i;

To access the string from the stringstream object,
use the member function str()
s.str()

To access the C string, use s.str().c_str()

Hope this helps
 
check portability itoa is NOT standard, and may not be supposrted by his compiler. In all likelyhood it is written using one of the methods posted above (string stream/sprintf).
 
hi,
there is no standard library function for itoa(reverse of atoi).
but u can get code for itoa function in k & ritchie text
book on C.try converting that code to c++ & use it.
i think it may help u out...
 
This template converts anything to a string as long as it has a stream operator defined for it (apologies if there are any typos we have an ancient Sun 4.3 C++ compiler which does not have stringstream so our version uses ostrstream)

template <class T> string mlToString(T thing)
{
stringstream conv;
conv << thing << ends; // not sure if &quot;ends&quot; necessary
return conv.c_str(); // COPY for return value
}

This works for all builtin types (int, float etc) and classes which already have a stream function defined. You might find it is not perfect for float output depending on your compiler's default output format.

For any other class you want to convert, define a stream function as follows:

ostream& operator<< ( ostream& arOS, const <class> &object)
{
// not sure if the &quot;ends&quot; are necessary
arOS << object.data1 << ends;
arOS << &quot;,&quot; << ends;
arOS << object.data1 << ends;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top