CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 1999
    Location
    Spain
    Posts
    335

    LPSTR, Why this function don't work ?

    Hi,

    This function gives an error, when tries to destroy the CString ( from the function in wich is called), Why fails this function ?

    /* -------------------------------------------------------------------------
    Replace the text given betwen iBeginRep and iEndReplace, with
    NewString
    ------------------------------------------------------------------------- */
    void CReplace::ReplaceString(CString &Text,int iBegin,int iEnd,CString &NewString)
    {
    int iNewSubStringLength = NewString.GetLength();
    int iOldSubStringLength = iEnd-iBegin+1; // To get the right length
    int iTextLength = Text.GetLength();
    ASSERT(iOldSubStringLength>=0);
    LPTSTR pText = NULL;
    LPTSTR pNewString = NULL;
    int iToRemove = 0;
    int iPos = 0;
    int iResize = 0;

    if (iNewSubStringLength==iOldSubStringLength) { // Only Replace
    pText = Text.GetBuffer(0);
    pNewString = NewString.GetBuffer(0);
    memcpy((pText+iBegin),pNewString,iOldSubStringLength);
    Text.ReleaseBuffer();
    NewString.ReleaseBuffer();
    } else {
    if (iOldSubStringLength>iNewSubStringLength) { // Replace and Move to right
    pText = Text.GetBuffer(0);
    pNewString = NewString.GetBuffer(0);
    memcpy(pText+iBegin,pNewString,iNewSubStringLength);
    NewString.ReleaseBuffer();
    Text.ReleaseBuffer();

    iPos = iBegin+iNewSubStringLength;
    iToRemove = iOldSubStringLength - iNewSubStringLength;
    DeleteChars(Text,iPos,iToRemove);
    } else { // Make Buffer Bigger,Move to left and Replace
    iResize = iNewSubStringLength-iOldSubStringLength;
    pText = Text.GetBuffer(iTextLength+iResize);
    pNewString = NewString.GetBuffer(0);

    int iDst = iBegin+iOldSubStringLength;
    int iSrc = iDst + iResize;
    memmove(pText+iSrc,pText+iDst,sizeof(_T(' '))*iResize);
    _tcsncpy(pText+iBegin,pNewString,iNewSubStringLength);
    //memcpy(pText+iBegin,pNewString,iNewSubStringLength);
    NewString.ReleaseBuffer();
    Text.ReleaseBuffer(iTextLength+iResize);
    }
    }
    }



  2. #2
    Guest

    Re: LPSTR, Why this function don't work ?

    Hi, I haven't check what could be wrong, but if I were you I would replace the code with:

    Text.Delete(iBegin, iEnd-iBegin+1);
    Text.Insert(iBegin, NewString);

    This should be used unless a really high performance is needed since the other code is much harder to read and more error prone.




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