有人能告诉我C/C++中c_str()函数的用途吗?在什么情况下需要使用它?
当您想要在C函数中使用字符串时
string s = "hello";
printf( "your string:%s", s.c_str() );
这是C++的问题,而不是C的问题。
c_str(来自于std::string
)的一个常见用法是将C++的std::string
转换为const char*
C字符串,这是许多底层C函数所需的(例如Posix系统调用,如stat
等)。
我猜你在问关于 string::c_str()
的问题?这是一个方法,它返回一个 string
对象的 C 字符串表示。例如,你可能需要一个 C 字符串表示来调用操作系统 API。