Solved

CString to char []

Posted on 1998-03-14
11
585 Views
Last Modified: 2013-11-19
I need to copy from CString to char[].  I read about the GetBuffer() and ReleaseBuffer() and wondering if it is needed here:

char Des[256] ;
CString Src = "Source" ;

if (Src.GetLength <= 255)
  strcpy (Des, Src) ; // no error

Or should it be

int n = Src.GetLength()
if (n <= 255)
{
 strcpy (Des, Src.GetBuffer(n)) ; // no error
 Src.ReleaseBuffer( );
}
0
Comment
Question by:leowlf
  • 3
  • 3
  • 2
  • +3
11 Comments
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316976
The MFC help referense says:
If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.

so, as long as you don't make any changes on the pointer you got, and in this case you don't there is no need in ReleaseBuffer
0
 

Author Comment

by:leowlf
ID: 1316977
What about this? No error. But is it technically correct?

    char Des[256] ;
    CString Src = "Source" ;

    if (Src.GetLength <= 255)
      strcpy (Des, Src) ; // no error
0
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316978
What do you mean by 'technicly correct'?
Everything is correct as long as it works, in programming there is no correct/not correct - IF IT WORKS, IT IS CORRECT
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 3

Expert Comment

by:stefanr
ID: 1316979
Probably a typo, but shouldn't the statement be
if (Src.GetLength() <= 255)`?
0
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316980
It should
0
 
LVL 11

Expert Comment

by:mikeblas
ID: 1316981
MikeP's answer is why the software industry is in such a shambles.  There _is_ a right and wrong; just because something "works" doesn't mean it is correct!

This is a science, not an art. Programmers need to work on getting things right, not hacking around until "it works".

.B ekiM
0
 

Author Comment

by:leowlf
ID: 1316982
I better reopen the question.
Is it technically correct if i do this without using GetBuffer(n) to do the copying?

char Des[256] ;
CString Src = "Source" ;

if (Src.GetLength() <= 255)
  strcpy (Des, Src) ;

I have not encounntered any error at runtime yet, but it could bomb out anytime if it done technically wrong.
0
 
LVL 1

Expert Comment

by:Nexial
ID: 1316983
Sorry, MikeP, but
"If it works,it is correct", is only valid if it is a ONE TIME
USE, throwaway program, that will neither be retained nor reused
nor supported.  i.e. a thrown together "HACK" to verify a fact
or check a response.   IT IS NOT SUITABLE FOR PRODUCTION CODE.
0
 
LVL 6

Accepted Solution

by:
jpk041897 earned 50 total points
ID: 1316984
Going back to your original question, GetBuffer() and ReleaseBuffer are not needed  to copy a CString to char[].

There are two ways you can access the char[] contained in a CString:

a) Casting via LPCSTR defined as:

 operator LPCTSTR ( ) const;

which returns a const char*.

b) GetBuffer defined as:

LPTSTR GetBuffer( int nMinBufLength );
throw( CMemoryException );

which returns a char *.

If all you intend is to copy the contents of the CString to an array then you would use:

    char Des[256] ;
    CString Src = "Source" ;

    if (Src.GetLength() <= 255)
      strcpy (Des, LPCSTR(Src)) ; // no error

since this code insures that the char[] contained in Src is not accidentaly modified.

You would need GetBuffer if you wanted to do the opposite, that is:



    char Des[256] ;
    CString Src = "Source" ;
    try{
       if (Src.GetLength() <= 255)
         strcpy (Src.GetBuffer(), Des) ; // no error
       }
    catch CMemoryException{
      // error procesing here
    }
  Src.ReleaseBuffer();
0
 
LVL 11

Expert Comment

by:mikeblas
ID: 1316985
JPK's "do the opposite" example is a little confusing and won't even compile.

In JPK's code, Des[] isn't initialized to anything. Caling strcpy() with it as the source string is likely to cause a crash. There's no reason to test the length of the existing string, as GetBuffer() takes a parameter for the minimum length the CString object will contain. Since JPK doesn't supply that parameter, the code won't compile.

It's not the missing parameter that's a problem: it's the idea that you have to call GetLength() that's confusing. You don't need to call GetLength()!  The parameter to GetBuffer() assures that you have at least that many chracters at the pointer returned from your GetBuffer() call.

Finally, GetBuffer() doesn't return a char*. It returns a LPTSTR. Sometimes, a char* is the same thing as a LPTSTR, but if _UNICODE is defined it certainly is not the same thing.

So, you should code the "going the other way" example like this:

TCHAR szSource[] = _T("Hockey is best!");
CString strDest;
try
{
   LPTSTR pstr = strDest.GetBuffer(lstrlen(szSource));
   lstrcpy(pstr, szSource);
}
catch (CMemoryException* pEx)
{
   // error processing here
   pEx->Delete();
}
strDest.ReleaseBuffer();

Of course, this example is completely academic because using GetBuffer() to assign a string to a CStr is completely unnecessary. You should just use the assignment operator:

TCHAR szSource[] = _T("Hockey is best!");
CString strDest;
strDest = szSource;

and get it done in one small call.

The bottom line is: using CString isn't that hard, and is very well-documented.  It's impossible for me to understand why this thread has gone on for so long and has so much dubious code and bad advice.

.B ekiM

0
 
LVL 11

Expert Comment

by:mikeblas
ID: 1316986
Oh, and JPK's exeception handler is wrong, too.  It won't compile, either... and never calls Delete() on the thrown object.

.B ekiM
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question