Hello,

I've had some problems converting a string into a char. I've tried many, many things, but it didn't seem to work.

I'll post the code below:

char filename[1024];
	char* url;
	string sUrl;


	HINTERNET hINet, hFile;
	hINet = InternetOpen("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
	if ( !hINet )
	{
		return false;
	}
	//
	int Page = 0;
	while(Page < 12)
	{
	sUrl+="";
	sUrl+=Server;
	sUrl+="&list=";
	sUrl+=Skill;
	sUrl+="&page=";
	sUrl+=Page;
	Page+=1;

	url = sUrl.c_str();
		cout << url << endl; 
		
		hFile = InternetOpenUrl( hINet, (char*)sUrl, ULL, 0, 0, 0 );
                  //The rest of the loop, no troubles here.

As you can see, I'm making a string that will contain the URL, I place the URL in it and then want to convert it to a char*.

I really tried about everything.

The URL doesn't neccesarely have to be a string, but I thought that would be the easiest way.

The errors that I get are:

Compiling...
TibiaName.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\TibiaName\TibiaName.cpp(169) : error C2440: '=' : cannot convert from 'const char *' to 'char *'
        Conversion loses qualifiers
C:\Program Files\Microsoft Visual Studio\MyProjects\TibiaName\TibiaName.cpp(173) : error C2440: 'type cast' : cannot convert from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char *'
        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Error executing cl.exe.

TibiaName.exe - 2 error(s), 0 warning(s)

line 169 is url = sUrl.c_str(); and line 173 is hFile = InternetOpenUrl( hINet, (char*)sUrl, ULL, 0, 0, 0 ); Greetz, Eddy


Edit: The error is in the strcpy() line, weird thing is that if I remove that line (put // before it) it still crashes. I will try to find out why.

Dani AI

Generated

Two issues are tripping you up here: const-correctness and the A vs. W (ANSI vs. Unicode) WinINet overloads. std::string::c_str() returns a read-only C string; assigning it to char* or casting away const (e.g., (char*)sUrl.c_str()) is wrong and can lead to UB if anything tries to modify it. Keep it as const char*, or better, pass it directly to the API. (en.cppreference.com)

Also note that InternetOpenUrl is a macro that maps to InternetOpenUrlA (expects LPCSTR) or InternetOpenUrlW (expects LPCWSTR) depending on whether UNICODE is defined. If you compiled with UNICODE, you must pass a wide string; otherwise, a narrow string is fine. (learn.microsoft.com)

One quick fix that avoids temporary buffers and strcpy: rebuild the URL fresh each iteration, then call the ANSI overload explicitly. This also fixes the bug where you keep appending to sUrl across loop iterations.

#include <sstream>

for (int page = 0; page < 12; ++page) {
    std::ostringstream os;
    os << "http://www.tibia.com/statistics/?subtopic=highscores&world="
       << Server << "&list=" << Skill << "&page=" << page;
    const std::string url = os.str();            // new string each time
    HINTERNET hFile = InternetOpenUrlA(hINet, url.c_str(), nullptr, 0, 0, 0);
    // use hFile...
}

If your project is UNICODE, build a std::wstring and call InternetOpenUrlW. For non-ASCII data, convert with MultiByteToWideChar (UTF-8 or ACP as appropriate) rather than a naive character-by-character copy. (learn.microsoft.com)

This aligns with ’s advice to pass c_str() directly, and with / on not writing through a c_str() pointer. Avoid the cast suggested by ; casting away const is a smell and unnecessary here. For background on passing STL strings to Win32 APIs, see Microsoft’s guidance. (learn.microsoft.com)

Recommended Answers

All 9 Replies

url = sUrl.c_str();

This won't work because you can't assign one Cstyle string to another. At the top of your code add the line #include <cstring>

and then use this:

strcpy(url, sUrl.c_str());

for the above line. There are other rules for using C style strings. If you are going to be using them routinely you should probably find a good C/C++ book and learn about them They are also called null terminated char arrays.

char* url;
	string sUrl;


	HINTERNET hINet, hFile;
	hINet = InternetOpen("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
	if ( !hINet )
	{
		return false;
	}
	//
	int Page = 0;
	while(Page < 12)
	{
	sUrl+="";
	sUrl+=Server;
	sUrl+="&list=";
	sUrl+=Skill;
	sUrl+="&page=";
	sUrl+=Page;
	Page+=1;

	strcpy(url, sUrl.c_str());
		cout << url << endl;
 
		
		hFile = InternetOpenUrl( hINet, url, NULL, 0, 0, 0 );
		if ( hFile )
--------------------Configuration: TibiaName - Win32 Debug--------------------
Compiling...
TibiaName.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\TibiaName\TibiaName.cpp(170) : warning C4700: local variable 'url' used without having been initialized
Linking...

TibiaName.exe - 0 error(s), 1 warning(s)

and craaaaaash... The program crashes without returning any data.
I didn't find the error yet by breakpoints. I will try to continue the search..
Thanks anyway

Greetz, Eddy

Remember where I said it would be a good idea to read about C style strings if you were going to use them? This is probably an example why.

url is declared as a char *, however it probably never had any memory given to it to point to. Therefore, when you try to write to it using the strcpy() call, boom. You can either change url to a fixed size char array using static memory, and make it big enough to hold any likely string you will end up putting into it, or you can use dynamic memory to make url just the right size.

//using dynamic memory
char * url;
url = new char[sUlr.length() + 1];
strcpy(url, sUlr.c_str());

//remember free up memory for url before using it again or when done with it by calling:
delete[] url;

You shouldn't have to bother with all that, since InternetOpenUrl expects LPCTSTR (typedef as const TCHAR*) as its second argument. Try:

hFile = InternetOpenUrl( hINet, sUrl.c_str(), NULL, 0, 0, 0 );

> char *url;
> url = sUrl.c_str();
Which got you
error C2440: '=' : cannot convert from 'const char *' to 'char *'
Understand that the c_str() method returns a const pointer for a reason, and that's to try and stop you from sneaking in the back door to change the string.

> char *url;
> strcpy(url, sUrl.c_str());
Which got you
warning C4700: local variable 'url' used without having been initialized
Yes, you used a variable before you initialised it.
Expect string data to be sprayed all over some unknown memory.

You can either allocate it as Lerner suggests,
Or simply have const char *url; to satisfy the const requirements.

Or just do what GloriousEremite showed, and scrap the whole temporary used once thing.

Hello,

I've had some problems converting a string into a char. I've tried many, many things, but it didn't seem to work.

I'll post the code below:

char filename[1024];
	char* url;
	string sUrl;


	HINTERNET hINet, hFile;
	hINet = InternetOpen("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
	if ( !hINet )
	{
		return false;
	}
	//
	int Page = 0;
	while(Page < 12)
	{
	sUrl+="";
	sUrl+=Server;
	sUrl+="&list=";
	sUrl+=Skill;
	sUrl+="&page=";
	sUrl+=Page;
	Page+=1;

	url = sUrl.c_str();
		cout << url << endl; 
		
		hFile = InternetOpenUrl( hINet, (char*)sUrl, ULL, 0, 0, 0 );
                  //The rest of the loop, no troubles here.

As you can see, I'm making a string that will contain the URL, I place the URL in it and then want to convert it to a char*.

I really tried about everything.

The URL doesn't neccesarely have to be a string, but I thought that would be the easiest way.

The errors that I get are:

Compiling...
TibiaName.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\TibiaName\TibiaName.cpp(169) : error C2440: '=' : cannot convert from 'const char *' to 'char *'
        Conversion loses qualifiers
C:\Program Files\Microsoft Visual Studio\MyProjects\TibiaName\TibiaName.cpp(173) : error C2440: 'type cast' : cannot convert from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char *'
        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Error executing cl.exe.

TibiaName.exe - 2 error(s), 0 warning(s)

line 169 is url = sUrl.c_str(); and line 173 is hFile = InternetOpenUrl( hINet, (char*)sUrl, ULL, 0, 0, 0 ); Greetz, Eddy


Edit: The error is in the strcpy() line, weird thing is that if I remove that line (put // before it) it still crashes. I will try to find out why.

------------------------------------------------

Hi instead of url=sUrl.c_str() u can write like

url=(char *)(sUrl.c_str())

leme know if u have any comments..

The easy way would be to have url as a char*. Or use different library. Microsoft library for strings has got the method to convert from string to char*, so if you would use it instead, you could convert your type by calling this method.

here it is

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
int l1,l2,i;

gets(str1);
gets(str2);
l1=strlen(str1);
l2=strlen(str2);

for(i=0;i<=l2;i++)
{
str1[i]=str2[i];
}
cout<<str1<<endl;
}
commented: fail fail fail -4

What an appalling piece of crap!
"void main" and using"gets()" - sheesh.
Not to mention the lack of code tags, the use of obsolete headers yada yada yada.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.