Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is this code safe? 1

Status
Not open for further replies.

LiquidBinary

Programmer
Jul 27, 2001
148
US
#include <string>
#include <iostream>

using namespace std;

char *String_Convert( const string &sConvert,
char *cString );
int main()
{
string sTest = &quot;Convert C++ string to C string.&quot;;
char *cTest = 0;

cTest = String_Convert( sTest,cTest );
cout << cTest;

delete [] cTest;

return 0;

}


char *String_Convert( const string &sConvert,char *cString )
{
int iSizeOfString = sConvert.length();
cString = new char[iSizeOfString+1];

for ( int i=0;i<iSizeOfString;i++ )
cString = sConvert;

cString = '\0';

return cString;
} Mike L.G.
mlg400@blazemail.com
 
I'm not sure why you should do this, you can get a constant C-string with sTest.c_str() which is fine say if you just want to write it to cout. If you need a modfiable string you can copy the value from c_str() with say strcpy(), which you have basically re-implemented in your String_Convert() function, i.e., your subroutine would look like

char *String_Convert( const string &sConvert,char *cString )
{
int iSizeOfString = sConvert.length();
cString = new char[iSizeOfString+1];

strcpy(cString,sConvert.c_str());
return cString;
}

But there's nothing actually wrong with your code, I would say. :) Hope that this helped! ;-)
 
Thanks Dave. Thats just what I was looking for. The reason for the code above is because I am just trying to minmize the headache that comes along with working with the win32 api. Most of the api calls only take C style strings as arguments when a string is needed. I figured that if I could do the string manipulations with a C++ string then transfer the contents into a C string to pass to the api call. How would you handle this? What is your opinion on CString vs. string? Mike L.G.
mlg400@blazemail.com
 
CString or string certainly makes things simpler if you are doing a lot of string manipulation, compared with using standard c-strings. If I was using MFC I'd go with CString, otherwise I'd use the string class. :) Hope that this helped! ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top