将字符串转换为const *字符
我有两个string
声明:将字符串转换为const *字符
killerName
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 */
看来,功能Notice
有const 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*
。我认为这就是你想要的。
正如其他人已经写道,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
的构造函数中。)
您的错误消息说明与您的问题相反。 – chris
这真的不清楚。输出和代码不符合您的问题或标题。 –
http://stackoverflow.com/questions/8126498/how-to-convert-a-const-char-to-stdstring – Brian