将字符串转换为 const* 字符
Converting string to const* char
我有两个string
声明:
-
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:"通知":无法将参数 1 从"std::basic_string<_Elem,_Traits,_Ax>"转换为"常量字符 */
函数似乎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*
提供给缓冲区。 我想这就是你想要的。
请参阅: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
构造函数中使用这种双重重载模式。
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 为什么 const int 适用于字符大括号初始化?
- 为什么我不能使用与"常量字符*"相同的"const int*"创建一个 int 数组?
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- std::转换为常量字符 * 的字符串在 std::unordered_set<const 字符 * 中找不到>
- 从 sub_match<常量字符 *>' 转换为'const char *const &'
- 将 const std::vector<char> 转换为无符号字符*?
- 如何从const char *类型字符串中删除新线字符
- 将字符数组添加到 const string&in C++
- 使用 const 指针的 C 样式字符返回不正确的结果
- ERROR字符和const字符
- C++:如何将'const char*'转换为字符
- C++ : 为什么我不能使用 sprintf 打印 const 字符*?
- 将 const 无符号字符* 分配给执行就地替换或省略的 std::string
- 赛格在一辆汽车上出错,从无符号的字符转换为 const 字符 在C++
- 通过连接另一个字符*初始化const字符*
- 比较 C++ 中的字符 - 类型为"char"的参数与类型为"const char * "的参数不兼容
- 存储const char*会给我随机字符