CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Aug 2001
    Location
    Germany
    Posts
    1,384

    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:
    charpChr 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.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    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

  3. #3
    Join Date
    Aug 2001
    Location
    Germany
    Posts
    1,384
    Thanks a lot!
    Usman.

  4. #4
    Join Date
    Jan 2002
    Location
    TamilNadu, India
    Posts
    158
    Why don't u try null terminating the char* and then assign it?
    Muthu

  5. #5
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    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


  6. #6
    Join Date
    Aug 2001
    Location
    Germany
    Posts
    1,384
    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
  •  





Click Here to Expand Forum to Full Width

Featured