[C++]Int to Char

Started by
17 comments, last by dxFoo 18 years, 7 months ago
I have an integer value, but I want it to be shown as a char. I don't mean ASCII values, I mean that if the int is equal to say, 128, I want the values 128 shown as chars. String class is applicable here too, probably would be easier for me? Thanks.
-Conrad
Advertisement
Look into the itoa() function. It is in the stdlib.h section.

link

Much luck!
with c++

do this

#include <sstream>
#include <string>

using namespace std;

string to_string( int val )
{
stringstream stream;
stream << val;
return stream.str();
}

// or more generally

template< class Type >
string to_string( Type val )
{
stringstream stream;
stream << val;
return stream.str();
}


i learned this yesterday, so i may be *very* wrong
rip-off is correct. Use stringstreams. In my opinion, they are the easiest way to do this. They're a great thing to have in your toolbox.
Wasn't there a thread recently in which someone explained why not to use stringstreams? (bad performance, memory leaks etc.) Anyway, I've seen a benchmark somewhere (not sure where) in which itoa() was about 6 times as fast as std::stringstream.
Quote:Original post by Kalasjniekof
Wasn't there a thread recently in which someone explained why not to use stringstreams? (bad performance, memory leaks etc.) Anyway, I've seen a benchmark somewhere (not sure where) in which itoa() was about 6 times as fast as std::stringstream.


There's something seriously, seriously wrong with your program if converting from a string to an int is a bottleneck. Speed is irrelevant. Memory leaks would be surprising, unless you forget to delete the characters you pass to it.
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Sorry for such a dumb question, I completely forgot about all the conversion functions, getting back into the C++ groove. ;)

Thanks guys
-Conrad
How about the old trusty sprintf? It's what I use most of the time.
Quote:Original post by parklife
How about the old trusty sprintf? It's what I use most of the time.


you misspelled snprintf there
Quote:Original post by rip-off
Quote:Original post by parklife
How about the old trusty sprintf? It's what I use most of the time.


you misspelled snprintf there

There's pretty much no reason to use snprintf in this situation.

This topic is closed to new replies.

Advertisement