【问题标题】:How to pass a string to const char* in C++?如何在 C++ 中将字符串传递给 const char*?
【发布时间】:2013-10-16 20:08:27
【问题描述】:

我试图在 C++ 中拆分 . 上的字符串,然后我需要将第一个拆分字符串传递给另一个接受 const char* key 的方法。但每次我这样做时,我总是会遇到异常 -

下面是我的代码 -

istringstream iss(key);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '.')) {
    if (!token.empty()) {
        tokens.push_back(token);
    }
}

cout<<"First Splitted String: " <<tokens[0] << endl;
attr_map.upsert(tokens[0]); //this throws an exception
}

下面是 AttributeMap.hh 文件中的 upsert 方法 -

bool upsert(const char* key);

下面是我经常遇到的例外 -

no matching function for call to AttributeMap::upsert(std::basic_string<char>&)

我有什么遗漏吗?

【问题讨论】:

  • 这既不是崩溃,也不是异常。那是编译器错误。您可以通过在适当的位置附加 .c_str() 并另外阅读文档来解决它。

标签: c++ string vector char


【解决方案1】:

使用c_str() 获取指向“以空字符结尾的字符数组,其数据与存储在字符串中的数据等效”的指针(引用自文档)。

attr_map.upsert(tokens[0].c_str()); //this won't throw an exception

【讨论】:

    【解决方案2】:

    你应该使用string::c_str

    attr_map.upsert(tokens[0].c_str())
                            //^^^
    

    c_str()函数的详细信息可以查看参考。

    您收到错误是因为 upsert 函数需要 const char*,但您传递的是 std::string,类型不匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 2022-01-25
      相关资源
      最近更新 更多