将字符串转换为const * char

时间:2014-04-03 22:55:31

标签: c++ string

我有两个string声明:

  1. killerName
  2. victimName
  3. 我需要将这两个字符串值转换为const * char。

    我如何使用我的方法的示例:

    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 :: basic_string< _Elem,_Traits,_Ax>'转换参数1到'const char * /

3 个答案:

答案 0 :(得分:4)

似乎函数Notice具有类型const char *的第一个参数但是表达式作为第一个参数传递给它

killerName + "has slain:" + victimName

的类型为std::string

只需按以下方式调用该功能

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

答案 1 :(得分:3)

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/

答案 2 :(得分:1)

正如其他人已经写过的那样,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 1}}版本在您的特定上下文中有意义;例如在{{1}}构造函数中使用此双重过载模式。)

相关问题