C++ 字符串兼容C 字符串
背景
在开发过程中经常会遇到C++字符串与C字符串的结合操作。
解决方法
C++ string类提供了c_str()函数。c_str()函数返回C风格字符串,即返回指向字符串数组首地址的指针,并且以 null结束。
例子
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
int main(){
//C++ 字符串
string s("test string");
//C++ 字符串转换成C字符串
const char * pt = s.c_str();
printf("%d\n",s.length());
printf("%d\n",strlen(pt));
}