Reputation: 143
I have two string
declarations:
killerName
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 */
Upvotes: 1
Views: 1406
Reputation: 42914
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.)
Upvotes: 1
Reputation: 310910
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);
Upvotes: 4
Reputation: 2524
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/
Upvotes: 3