c++中c_str()的用法是什么

c++
173
2024/3/28 18:05:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,c_str()是一个成员函数,可用于将std::string对象转换为C风格的字符串(以null结尾的字符数组)。这在需要将std::string对象传递给接受C风格字符串作为参数的函数或库时非常有用。

例如:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    
    const char* cstr = str.c_str();
    
    std::cout << "C-style string: " << cstr << std::endl;
    
    return 0;
}

请注意,c_str()函数返回的指针指向std::string对象内部的字符数组,因此当std::string对象被销毁时,该指针将变为悬空。因此,应谨慎使用c_str()函数,确保在其返回的指针不再需要时不再使用。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++智能指针的实现原理是什么