Solved

CString to char []

Posted on 1998-03-14
11
587 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Need a Shell script to start a service checking the port 6 56
MFC Dialog 9 54
How to know only "File created" with EventLog 3 35
mapAB Challlenge 35 186
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…
Introduction: Load and Save to file, Document-View interaction inside the SDI. Continuing from the second article about sudoku.   Open the project in visual studio. From the class view select CSudokuDoc and double click to open the header …
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.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

738 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