1
votes

I have two string declarations:

  1. killerName
  2. victimName

I need to convert these two string values to const* char.

Example of how I use my method:

if (killer.IsRealPlayer) {
   killerName = killer.GetName(); -- need to convert to const* char
   victimName = victim.GetName(); -- need to convert to const* char

   Notice(killerName + "has slain:" + victimName, killer.GetMapIndex(), false); 
}

Some error I receive:

Error 111 error C2664: 'Notice' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char */

3
Your error message says the opposite of your question.chris
This is really unclear. The output and code do not match your question or title.Lightness Races in Orbit
Yeah... my bad.. i will edit it in few seconds. Sorryuser3281950
And your new edit is completely off-target. Do you know what happens if you do const char* + "has slain:" + const char* ?Ben Voigt

3 Answers

4
votes

It seems that function Notice have the first parameter of type const char * However the expression passed to it as the first argument

killerName + "has slain:" + victimName

has type std::string

Simply call the function the following way

Notice( ( killerName + "has slain:" + victimName ).c_str(), killer.GetMapIndex(), false); 
3
votes
Notice(string(killerName + "has slain:" + victimName).c_str(), killer.GetMapIndex(), false); 

std::string::c_str() gives the const char* to the buffer. I think that's what you want.

See: http://www.cplusplus.com/reference/string/string/c_str/

1
votes

As others already wrote, the result of killerName + "has slain:" + victimName is of type std::string. So, if your Notice() function expects a const char* as first parameter, you must convert from std::string to const char*, and since there is no implicit conversion defined for std::string, you must call the std::string::c_str() method:

Notice((killerName + "has slain:" + victimName).c_str(), killer.GetMapIndex(), false); 

However, I'd like to ask: why do you have Notice() expecting a const char* as first parameter?
Would it be better to just use const std::string&? In general, in modern C++ code, you may want to use string classes like std::string instead of raw char* pointers.

(Another option would be to have two overloads of Notice(): one expecting a const std::string& as first parameter, and the other one expecting a const char*, if for some reason the const char* version does make sense in your particular context; this double overload pattern is used e.g. in the std::fstream constructor.)