tags:

views:

140

answers:

5
#include <iostream>

using namespace std;

int main()
{
     char buffer[8];
     int field=534;
     memcpy(buffer,&field,sizeof(field));
     cout<<buffer<<endl;

     return 0;
}

This returns an empty buffer. Why?

Basically looking for an alternative to sprintf to convert int to char buffer.

Itoa is not available.

Thoughts? Better alternatives?

+2  A: 

If itoa if available you can use it, this function is not not part of C++, but is supported by some compilers.

Alternatively you can do:

std::stringstream out;
out << field;
strcpy(buffer,out.str().c_str());
codaddict
It is part of the C standard lib so ill be in any conforming C or c++ compiler
Mark
itoa is not available
windfinder
@Mark: No, `itoa` is *not* part of the C standard library. The C standard function to do this is `sprintf()`.
caf
Ok I misread some of the man pages etc
Mark
+4  A: 

You will have to use sprintf or itoa to convert a binary int to an ascii string.

The representation if ints and and char arrays is totally different and ints can conytain bytes with a value of zero but strings can only have that as the last byte.

for example

Takes 0 - in int it is represented by 4 bytes with values 0 whilst ) as a string has the first two bytes of 48 and 0 so no simple cast will chnage this

Mark
+2  A: 

You can use also istringstream:

istringstream ss(field);
ss>>buffer;
rursw1
+1 for a C++ approach! Does that really work though? I'm not sure. I although use `ostringstream oss; oss << field;` and use oss.str() instead of a buffer....
Tony
+1  A: 

Your method isn't going to work due to both the encoding of char's and the fact '9' != 9. But why not just build your own itoa? Its very simple(hint: x - '0' will turn '0' - '9' into 0 - 9), alternatively just copy the source for an itoa varient from any one of the open source libstdc's

Necrolis
+1 for build your own.
C Johnson
+3  A: 

I think the memcpy has succeeded. Memcopy is going to copy the bytes and not translate the bytes in to characters (as you want to do). You can't see because 534 happens to produce two non-printable characters. Try using 18505 and it'll print a message. Not what you want though.

If itoa isn't available then you could always write your own. In fact that's a common computer science homework problem. To do it you need to get each digit seperated from the integer (hint integer division will truncate - just what we want!) and you'll need to convert each digit from an integer between 0 and 9 and it's ascii representation.

That's enough hints but if you need more help then feel free to ask.

dave