Convert std::string to const char*

I am trying to convert a std::string to a const char*. This is with GetHostByName(). Any help is appreciated. This is what I have sp far.

1
2
3
4
5
6
7
8
9
10
int Newlength = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0,  NULL, NULL); 
std::string NewLogURL(Newlength+1, 0); 
int Newresult = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, &NewLogURL[0],Newlength+1,  NULL, NULL); 
		
HOSTENT *pHostEnt;
int  **ppaddr;
SOCKADDR_IN sockAddr;
char* addr;
		
pHostEnt = gethostbyname(NewLogURL);

Last edited on
The std::string::c_str() method returns a const char*.
OK, webJose. But how would I implement it into this code? Thank you.
1
2
string sExample = "Text";
const char * ccpExample = sExample.c_str ();
I think what you want is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int Newlength = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0,  NULL, NULL); 
// allocate buffer
char* buffer = new char[Newlength]; // this INCLUDES terminating NULL if you use -1 argument to WideCharToMultiByte()
WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, buffer, Newlength,  NULL, NULL);
DWORD dwError = GetLastError();

 HOSTENT *pHostEnt;
int  **ppaddr;
SOCKADDR_IN sockAddr;
char* addr;
		
pHostEnt = gethostbyname(buffer);
delete [] buffer; // free memory


 // code here






If you have a paid for version of Visual Studio, you can use ATL CT2A() macro .
Last edited on
Thank you. I tried it and got this....

Current Website URL: cplusplus.com


Current Website IP:ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε
ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε

The code as run...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Newlength = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0,  NULL, NULL); 
// allocate buffer
char* buffer = new char[Newlength]; // this INCLUDES terminating NULL if you use -1 argument to WideCharToMultiByte()
WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, buffer, Newlength,  NULL, NULL);
	DWORD dwError = GetLastError();
	HOSTENT *pHostEnt;
	int  **ppaddr;
	SOCKADDR_IN sockAddr;
	char* addr;
		
	pHostEnt = gethostbyname(buffer);
               //Added this on the second run, same results////////////////
                ppaddr = (int**)pHostEnt->h_addr_list;
	sockAddr.sin_addr.s_addr = **ppaddr;
	addr = inet_ntoa(sockAddr.sin_addr);
               ////////////////////////////////////////////////////
	delete [] buffer; // free memory
	printf("\n   Current Website IP:%s", buffer);
Why are you deleting buffer before you print it?
Topic archived. No new replies allowed.