Solved

CString to char []

Posted on 1998-03-14
11
583 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 3

Expert Comment

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

Expert Comment

by:MikeP090797
Comment Utility
It should
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 11

Expert Comment

by:mikeblas
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Here is how to use MFC's automatic Radio Button handling in your dialog boxes and forms.  Beginner programmers usually start with a OnClick handler for each radio button and that's just not the right way to go.  MFC has a very cool system for handli…
Introduction: Dynamic window placements and drawing on a form, simple usage of windows registry as a storage place for information. Continuing from the first article about sudoku.  There we have designed the application and put a lot of user int…
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.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now