Click to See Complete Forum and Search --> : Copying NOT null terminated C-string to std::string


usman999_1
April 9th, 2003, 09:47 AM
Hi *!
I get from a lib a not null-terminated string back. I am want to copy it to my local std::string. I also get back the total length of C-string. Here is what i am doing

char* pChr = NULL;
short nChrLen = 0;
std::string szMyString = "";
// Call some lib functions with pChr and &nChrLen....
if(pChr){
szMyString = pChr;
szMyString[nChrLen] = '\\0';
}

It works correctly but is it the corrrect way, coz if i don't null terminate the string i get some junk stuff (thats obvious) but the copying of string reads some part of memory that it is not supposed to. Whats the correct way to do that????????
Thanks in Advance,
Regards,
Usman.

Paul McKenzie
April 9th, 2003, 10:19 AM
Originally posted by usman999_1
Hi *!
I get from a lib a not null-terminated string back. I am want to copy it to my local std::string.
Use the std::string::assign() member function:

szMyString.assign(pChr, nChrLen);

Regards,

Paul McKenzie

usman999_1
April 9th, 2003, 10:39 AM
Thanks a lot!
Usman.

muthuis
April 11th, 2003, 05:04 AM
Why don't u try null terminating the char* and then assign it?

Graham
April 11th, 2003, 05:06 AM
Originally posted by muthuis
Why don't u try null terminating the char* and then assign it?
Because std::string::assign exists.

usman999_1
April 11th, 2003, 05:07 AM
Well as i earlier described in my post that memory is not allocated in my program. I dont want to modify that memory that i dont know of.
Regards,
Usman.