|
-
April 9th, 2003, 09:47 AM
#1
Copying NOT null terminated C-string to std::string
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
PHP Code:
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.
-
April 9th, 2003, 10:19 AM
#2
Re: Copying NOT null terminated C-string to std::string
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:
Code:
szMyString.assign(pChr, nChrLen);
Regards,
Paul McKenzie
-
April 9th, 2003, 10:39 AM
#3
-
April 11th, 2003, 05:04 AM
#4
Why don't u try null terminating the char* and then assign it?
Muthu
-
April 11th, 2003, 05:06 AM
#5
Originally posted by muthuis
Why don't u try null terminating the char* and then assign it?
Because std::string::assign exists.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
April 11th, 2003, 05:07 AM
#6
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|