【问题标题】:How to append char pointer to std::string in C++如何在 C++ 中将 char 指针附加到 std::string
【发布时间】:2021-09-08 10:02:44
【问题描述】:
  char * val = ep->GetValue();
  std::string m="zValue:" + (std::string)val;

ep->GetValue() 返回一个字符指针。我想将它附加到一个字符串。我按照上面的方法尝试了,但它会引发以下错误。

terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_construct null not valid

【问题讨论】:

  • 我明白val == nullptr...所以错误
  • 虽然与您的问题无关,但几乎任何时候您觉得需要进行 C 风格转换或转换(就像您对 (std::string)val 所做的那样),您应该将其视为您正在做的标志有事吗。如果要创建字符串,请使用std::string(val) 显式执行。
  • ep_>GetValue() 返回空值。当ep->GetValue() 返回 null 时,您希望字符串是什么样的?

标签: c++ string


【解决方案1】:

您收到此错误是因为您尝试从 nullptr 构建 std::string。试试:

std::string m = "zValue:";
if(char * val = ep->GetValue()) m += val;

【讨论】:

    【解决方案2】:

    或以可重复使用的形式:

    #include <string>
    #include <iostream>
    
    std::string string_from_ptr(const char* p)
    {
        std::string retval;
        if (p != nullptr) retval = p;
        return retval;
    }
    
    
    int main()
    {
        char* p{ nullptr };
        std::cout << string_from_ptr(p);
        // auto str = string_from_ptr(ep->GetValue());
    }
    

    【讨论】:

    • 糟糕 ;) 修复了它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2023-03-06
    • 2012-07-05
    相关资源
    最近更新 更多