【问题标题】:hot to convert std::__cxx11::string to std::string [closed]将 std::__cxx11::string 转换为 std::string [关闭]
【发布时间】:2020-03-28 05:57:28
【问题描述】:

所以我只想将 int 转换为数字并将其存储在数组中

例如

int n=456;

std::string nstr = std::to_string(n);

std::cout << nstr[0];

现在我只想要nstr的长度...

每当我使用std::strlen(nstr);

它给出一个错误

**error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'**

请告诉我如何将std::__cxx11::string 转换为std::string

或者有没有其他方法可以计算nstr的长度

【问题讨论】:

  • 为什么使用strlen() 而不是std::string::size()
  • strlen 用于字符数组,你可以使用nstr..size()
  • std::string 有一个 sizelength 成员函数可以为您执行此操作。 strlen 用于 c 字符串,而不是 std::strings
  • 不仅使用strlen() 不正确,对strlen() 的调用是O(n) 操作,其中n 是字符数(包括)终止空值。对size() 的调用是O(1) 操作,因为std::string 知道存储的字符数而无需查找空值。因此,即使您的代码可以使用 strlen,它也比使用 size 慢。
  • std::__cxx11::string std::string。您的错误显然是关于转换为const char*,而不是转换为std::string,所以我不明白您为什么在问题标题和正文中询问后者...

标签: c++ string c++11 casting stdstring


【解决方案1】:

热转换 std::__cxx11::string 为 std::string

std::__cxx11::string (名称)std::string 在您使用的标准库实现中。

std::string 不能传递给 std::strlen,因为它要求参数改为 const char*,如错误消息中所述。

或者有没有其他方法可以计算nstr的长度

通常,您应该使用size 成员函数。但是不涉及计算。大小是在创建字符串时计算的,然后存储在字符串对象中。

【讨论】:

    【解决方案2】:

    如果你真的,真的,真的想使用strlen(),你必须转换成char*

    std::strlen(nstr.c_str());
    

    但通常你只会询问字符串的大小:

    nstr.size();
    

    我能想到你可能更喜欢strlen() 的唯一原因是你的字符串中嵌入了空值,并且你想在那里停止计数。

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 2016-06-10
      • 2021-10-28
      • 2018-03-11
      相关资源
      最近更新 更多