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!

string to char*

Status
Not open for further replies.

hectorDUQUE

Programmer
Jan 29, 2007
23
hi guys,
i am getting problems trying to convert a c++ basic string to a char * (C languaje).

error: cannot convert ‘std::string’ to ‘char*’ for argument ‘1’ to ‘void hD_readIniFile(char*, map_group_type&, map_groupFN_type&)’

Code:
  string fn_ch(*cur_edge);
  hD_readIniFile(fn_ch, groupOfNumbers, groupsFN);

is there a function to convert this ?

thanks in advance

hector
 
Do you need a char* or const char*?

If the hD_readIniFile function changes the string inside fn_ch, then it will need to be a char*, but if it doesn't change the string then that function should take a const char*. If that is the case, just pass fn_ch.c_str().

If you are sure that the function will not modify the value, but it cannot be changed to take a const char*, then you can cast away the constness of c_str(). This is not ideal, but if you know the string won't change it should be safe:
Code:
string fn_ch(*cur_edge);
hD_readIniFile(const_cast<char*>(fn_ch.c_str()), groupOfNumbers, groupsFN);
Finally, if the function is going to modify the string, then you will need to make a modifiable copy of the string. The easiest way to do this if you don't know the size at compile time is with a vector, since that will clean up its own memory automatically:
Code:
vector<char> fn_ch(cur_edge->begin(), cur_edge->end());
fn_ch += '\0';
hD_readIniFile(&fn_ch[0], groupOfNumbers, groupsFN);
Note that in that example there is only enough space for the number of characters in cur_edge. If you need more space then you need to make the vector bigger. If you know at compile time how much space there is, you can use an array and strcpy the contents of the string into the array as well.
 
What other forum was this question posted on?

The other thread you made that comment on was a completely different topic than this one and by a different poster, if that is what you were referring to.
 
I don't see the double post. One post asked about converting string to char*. Another asked about converting char* to int. One was made by hectorDUQUE, the other by Bigbass.

Please look more closely next time. :)
 
Oops... Maybe I should look more closely next time. I see that the other post is in the C forum.

Never mind!

:p
 
You're half correct. The post in forum 205 is the duplicate. Even with that error, my comment still stands because he posted the same question in 2 forums.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top