Ural Mutlu wrote:
> On Wed, 26 Jul 2006 04:39:38 +0100, Ural Mutlu wrote:
>
>> Hi,
>>
>> I have an array of int's and a string. I am trying to copy the int array
>> into the string but I haven't been successful. The only solution I can
>> think of is strcpy or memcpy.
>>
>> I wrote the following test program but in the example below str is empty.
>>
>> I thought of using itoa() in the stdlib.h but itoa() must be obsolete,
>> gcc doesn't find the function.
>>
>> Any suggestions?
>>
>> OS: linux
>> compiler: gcc v:4.1.1
>>
>>
>> #include <iostream>
>> #include <string>
>>
>> using namespace std;
>>
>> int main() {
>>
>> string str("");
>> int i[2]={0,0};
>>
>> strncpy((char*)str.c_str(),(char*)i, sizeof(i));
>> //memcpy((void*)str.c_str(),(void*)i, sizeof(i));
>> cout<<str<<endl;
>> return 0;
>> }
>>
>>
>> Regards
>
> I should probably add that I am not looking to convert the int's to
> char's.
Yes.
> I mean if the size of int is 4 bytes, I have to represent it as 4 char's.
> Basically, some data is stored in a string rather than int.
>
> That's why I thought memcpy is the solution, but somehow the above
> example doesn't give me a result.
Try:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
string str("");
int i[2]={48908902,4090799};
char const * c_begin
= static_cast< char* >( static_cast< void* >( &i[0] ) );
char const * c_end = c_begin + sizeof(i);
copy( c_begin, c_end, inserter( str, str.end() ) );
cout<<str<<endl;
return 0;
}
Beware that the code is bound to invoke undefined behavior as the standard
does not impose rigid restrictions on the internal representation of
integers. In particular, you may find that endian-ness enters the picture.
Best
Kai-Uwe Bux
|