将字符串转换为const *字符

问题描述:

我有两个string声明:将字符串转换为const *字符

  1. killerName
  2. victimName

我需要这两个字符串值转换为const *字符。

我如何用我的方法

例子:

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); 
} 

一些错误我收到:

错误111错误C2664: '通知':无法从“STD转换参数1 :: basic_string的< _Elem,_Traits,_AX> '到' 为const char */

+1

您的错误消息说明与您的问题相反。 – chris

+0

这真的不清楚。输出和代码不符合您的问题或标题。 –

+0

http://stackoverflow.com/questions/8126498/how-to-convert-a-const-char-to-stdstring – Brian

看来,功能Noticeconst char *类型的第一个参数,但是表达传递给它的第一个参数

killerName + "has slain:" + victimName 

的类型为std::string

只需调用功能如下

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

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

std::string::c_str()给出了缓冲区的const char*。我认为这就是你想要的。

参见:http://www.cplusplus.com/reference/string/string/c_str/

正如其他人已经写道,killerName + "has slain:" + victimName的结果是std::string类型。所以,如果你Notice()函数需要const char*作为第一个参数,你必须从std::string转换为const char*,而且由于没有用于std::string没有定义转换,则必须调用std::string::c_str()方法:

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

然而,我想问一下:为什么你有Notice()期待const char*作为第一个参数?
只使用const std::string&会更好吗?一般来说,在现代C++代码中,您可能希望使用像std::string这样的字符串类而不是原始的char*指针。

(另一种选择是有Notice()两个重载:一个期待const std::string&作为第一个参数,而另一个期待const char*,如果由于某种原因,const char*版本有一定道理在你的特定背景下,这种双重过载保护图案用于例如std::fstream的构造函数中。)