租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

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

发布时间:2024-04-07 18:05:34

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

在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()函数,确保在其返回的指针不再需要时不再使用。