【问题标题】:std::string to const char array [duplicate]std::string 到 const char 数组 [重复]
【发布时间】:2015-11-07 22:40:48
【问题描述】:

这是我想要做的代码

std::string json_str;
const char json[] = json_str;

这是我的尝试

const char json [json_str.size()] = {(char) json_str.c_str ()};

但它给了我错误“从 'const char*' 转换为 'char' 失去精度”

请帮忙。谢谢你。

【问题讨论】:

  • 使用 json_str.c_str() 它将返回一个 const char *.
  • C++ 没有可变长度数组。数组的维度必须来自编译时常量。
  • 不能从编译时无法归约的表达式中直接赋值给数组。
  • 当你有字符串时,你是否有理由需要const char*?如果你有一个接受const char* 的函数,那么只需使用json_str.c_str() 作为参数。
  • @NathanOliver 我想你是对的; document.Parse (json_str.c_str()) 确实编译;现在看看它是否有效

标签: c++ rapidjson


【解决方案1】:
#include <string>

int main() {
    std::string json_str;
    const char *json = json_str.c_str();
    return 0;
}

【讨论】:

  • 这应该伴随着json所指向的缓冲区的生命周期的简短讨论。
【解决方案2】:

想到的可能解决方案:

std::string json_str;
const char* json = json_str.c_str();

只要json_str 还活着,你就可以使用json

std::string json_str;
const char* json = strdup(json_str.c_str());

即使json_str 不存在,您也可以使用json,但您必须确保释放内存。

【讨论】:

    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2011-10-26
    相关资源
    最近更新 更多