CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1

    CString's GetLength mystery

    I was testing a variable, the following are two lines:

    TRACE(m_strDirectory);
    TRACE("\nlength: %d\n", m_strDirectory.GetLength());

    and the output is:

    D:\Projects
    length: 0

    how come? Why the length is zero?

    Thanks!
    Sway

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: CString's GetLength mystery

    The following works fine for me.

    Code:
    void CTraceTestDlg::OnBnClickedOk()
    {
    	CString sDirectory( _T("D:\\Projects") );
    
    	TRACE( sDirectory );
    	TRACE( _T("\nlength: %d\n"), sDirectory.GetLength( ) );
    }
    Prints out:
    Code:
    D:\Projects
    length: 11
    What version of Visual C++ are you using?

  3. #3
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: CString's GetLength mystery

    how come? Why the length is zero?
    Did you use GetBuffer to fill the string (and not use releasebuffer to mark the length of the string) ?

  4. #4

    Re: CString's GetLength mystery

    Thank you both. Arjay: the VC is 9.0; Skizmo: you are right. I used GetBuffer to fill the string and didn't releaseBuffer. Now it's fine. But can you eleborate on it, or give me a link to read?

    Thanks again!

  5. #5
    Join Date
    Feb 2009
    Location
    India
    Posts
    444

    Re: CString's GetLength mystery

    CString maintains an internal count.

    Normally the CString constructor or operators like =, += or functions like Format, Insert, Replace etc. are used to modify the CString object. All these methods will update the internal count.

    GetBuffer on the other hand exposes the internal buffer in the CString object.
    All operations on this buffer are not recorded by the object.
    Its only when ReleaseBuffer is called that the internal count is updated.

    If you expose the internal buffer using GetBuffer for read only access, it is not necessary to call ReleaseBuffer as nothing is modified.
    «_Superman
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: CString's GetLength mystery

    See the documentation for GetBuffer in msdn.

    Unfortunately, the docs for CString kind of suck, so you'll need to speed some time looking around and the different methods.

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