【问题标题】:Converting string to const* char将字符串转换为 const* char
【发布时间】:2014-05-16 00:58:17
【问题描述】:

我有两个string 声明:

  1. killerName
  2. victimName

我需要将这两个字符串值转换为 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); 
}

我收到一些错误:

Error 111 error C2664: 'Notice' : 无法将参数 1 从 'std::basic_string<_elem>' 转换为 'const char */

【问题讨论】:

  • 您的错误信息与您的问题相反。
  • 这个真的不清楚。输出和代码与您的问题或标题不匹配。
  • 是的......我的错......我会在几秒钟内编辑它。对不起
  • 而且您的新编辑完全脱靶。你知道如果你这样做const char* + "has slain:" + const char* 会发生什么吗?

标签: c++ string


【解决方案1】:

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

killerName + "has slain:" + victimName

有类型std::string

只需按以下方式调用函数

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

【讨论】:

    【解决方案2】:
    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/

    【讨论】:

      【解决方案3】:

      正如其他人已经写的那样,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&amp; 会更好吗?通常,在现代 C++ 代码中,您可能希望使用 std::string 之类的字符串类,而不是原始的 char* 指针。

      (另一种选择是有两个Notice() 重载:一个期望const std::string&amp; 作为第一个参数,另一个期望const char*,如果由于某种原因const char* 版本在您的特定上下文;这种双重重载模式例如在 std::fstream 构造函数中使用。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-08
        • 2013-02-15
        • 1970-01-01
        • 2015-12-19
        • 2016-04-20
        相关资源
        最近更新 更多