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

2024-04-29

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