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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cstring to char* 1

Status
Not open for further replies.

A1METALHEAD

Programmer
May 21, 2004
76
US
are there any convertions between CString and char*? i hate CString... and i need a way to get a char*...
thanks,
~metalhead
 
CString is basicly a wrapper around char*, so it has operator(char*) (or rather LPCTSTR) and a base member which is a char*, so yes you can convert easily between the two.

------------------------
dev at viewmoresoft.com
tools for your database
 
A1METALHEAD, this is how I do my conversions.

CString str;
int iSize;
char p*;

str = "Hello";
iSize = str.GetLength(); //get size of string

p = (char*)malloc(iSize); //initialize char* to size of string

strcpy(p,str);
free(p);

I hope this helps.
 
krussell1711, shouldn't you add an extra character to that length for the terminating null?

Anyway, use the implicit cast to LPCTSTR if you want a const char* and use GetBuffer/ReleaseBuffer if you want a char* that will directly manipulate the contents of the CString, and use something similar to krussell1711's solution using strcpy if you want a char* that doesn't affect the data in the CString.
 
uolj, you are right.

it should be iSize = str.GetLength() + 1; //get size of string

Thanks for the correction.
Krussell1711
 
thanks, but i still get an accses violation with this code:

Code:
void chatAboutDlg::OnBnClickedSend()
{
	int iSize;
	char* p;

	iSize = ipAddress.GetLength(); //get size of string

	p = (char*)malloc(iSize); //initialize char* to size of string

	strcpy(p,ipAddress);
	free(p);

	winChat = new winChatApp( 1200 , p );
	m_send.SetWindowText("Send");
	m_sendtextCon.SetWindowText("");
}
 
This how your code should look.

void chatAboutDlg::OnBnClickedSend()
{
int iSize;
char* p;

iSize = ipAddress.GetLength() + 1; //get size of string

p = (char*)malloc(iSize); //initialize char* to size of string

strcpy(p,ipAddress);

winChat = new winChatApp( 1200 , p );
m_send.SetWindowText("Send");
m_sendtextCon.SetWindowText("");

free(p); //always free memory before exiting function or you could have a memory leak.
}

I hope this helps.
Krussell1711
 
Does the winChatApp constructor take a char * or a const char *? It looks like it just wants a string, so it should probably take a const char*, in which case there is no need to copy the string first, just pass the CString (and it will be implicitly converted to const char*).

However, if the winChatApp requires a char*, and since you are using new/delete in your code already, I would go ahead and use them instead of malloc for the string:
Code:
void chatAboutDlg::OnBnClickedSend()
{
    char* tmpIP = new char[ipAddress.GetLength()+1];
    strcpy(tmp, ipAddress);

    winChat = new winChatApp( 1200 , tmpIP );
    delete [] tmp;

    m_send.SetWindowText("Send");
    m_sendtextCon.SetWindowText("");
}
 
well... thanks both of you, but i get "Unhandled exception at 0x004a3520 in chat client.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd."... here are my locals:
Code:
-	this	0x00a731d0 {isSetup=true itsSocket=-842150451 portNum=-842150451 ...}	winChatApp * const
	isSetup	true	bool
	itsSocket	-842150451	int
	portNum	-842150451	int
	bytes	-842150451	int
-	ip	0xcdcdcdcd <Bad Ptr>	char *
		CXX0030: Error: expression cannot be evaluated	char
-	lastSnd	0xcdcdcdcd <Bad Ptr>	char *
		CXX0030: Error: expression cannot be evaluated	char
-	lastRcv	0xcdcdcdcd <Bad Ptr>	char *
		CXX0030: Error: expression cannot be evaluated	char
	port	1200	int
-	aIp	0x00a73190 ""	char *
		0	char

it must be somthing im doing wrong then...
 
oh! sorry, here is my decleration:
Code:
class winChatApp
{
public:
	winChatApp(int,char*);
	~winChatApp();

	bool isSetup;
	char* rev();
	bool send(char*);
private:
	int itsSocket;
	int portNum;
	int bytes;

	char* ip;
	char* lastSnd;
	char* lastRcv;

	int startupClient();
	void shutdownClient();
};
and here is my contructor:
Code:
winChatApp::winChatApp(int port , char* aIp)
{
	strcpy( ip , aIp );
	portNum = port;
	itsSocket = startupClient();

	if (itsSocket == -1) 
	{
		shutdownClient();
		return;
	}
	isSetup = true;
}
 
ok... i got it... sorry for my stupidity... i forgot to initilize the ip string in the constructor... sorry! and thanks for all yourt help!
 
Given that code, I would change the winChatApp constructor to:
Code:
winChatApp::winChatApp(int port , [red]const[/red] char* aIp)
that way you can simply pass the CString to the constructor without any explicit conversion:
Code:
void chatAboutDlg::OnBnClickedSend()
{
    winChat = new winChatApp( 1200 , ipAddress );
    m_send.SetWindowText("Send");
    m_sendtextCon.SetWindowText("");
}
Much easier, and more "correct".
 
hello agin... it turns out it dosent work... and i think it has to do with my member vars not working rihgt... im using MFC with VC++2003.net, and i added the var by right-clicking the controll, selecting value on a drop-down list, then typing in the var name... but, no-matter what i do, the string is always blank! can somne help? thanks...
~metalhead
 
OK, I understand that this post is a couple of weeks old, but I am running into a similar problem, my CString's will not convert into const char *'s did anyone ever conclude this thread? I have found that the method mentioned by uolj works fine in VC++ 6.0 however it seems to no work in the .NET 2003 version. I am working on upgrading projects from 6.0 into .NET and running into this problem...does anyone have suggestions? or even a link to a good MSDN help section...
 
Well, easy retieval of CString as const char* (using the LPCTSTR operator) only works in non-unicode build, since LPCTSTR then translates to a const w_char*.

My solution to, no matter what, get it as const char* is
Code:
#include <string>

std::string lpctstr2string(LPCTSTR s_in)
{
#ifdef _UNICODE
	std::wstring w(s_in);
	std::string s;

	for(std::wstring::const_iterator it = w.begin();it!=w.end();++it)
		s+=(*it);
	return s;
#else
	return s_in;
#endif
}
which actually retrives it as a std::string, but anyway.

Ie
Code:
  CString strHello("Hiya");
  cout << lpctstr2string(strHello).c_str() << endl;

works as expected in both unicode and non-unicode.



/Per
[sub]
www.perfnurt.se[/sub]
 
ok so i looked at my code and I actually need it as just a char * not a const...I tried some of the above methods, but it won't implicitly cast to a const char * for the strcpy function. I am in UNICODE so do I have to use this method? or is there an easier/shorter way?
 
>will the GetBuffer() function work?

Yes, if you use _tcscpy instead of strcpy.

/Per
[sub]
www.perfnurt.se[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top