- 前引
- 1. Convert string to const char*
- 2. Convert string to char*
- 3. Convert string to int
前引
博主经常遇见需要将string类转换为const char*,char *的要求,因为函数的参数只接收char * / const char*的参数,如SQLConnect。
1. Convert string to const char*
method①:
const char* constCharPtr = object.data();
string:data()
method②:
const char* constCharPtr = object.c_str();
string::c_str()
string::data()与string::c_str()区别在于前者指向的字符数组不以‘\0’结尾。
2. Convert string to char*
method①:
char* charPtr = const_cast<char*>(object.data());
char* charPtr = const_cast<char*>(object.c_str());
const_cast用于消除对象的const属性
const_cast
method②:
int len = object.size();
char* charPtr = new char[len+1];
copy(object.cbegin(), object.cend(), charPtr);
charPtr[len] = ';'int
用标准算法copy(),需包含头文件
Convert a std::string to char* in C++
3. Convert string to int
method①:
= intObject atoi (.objectc_str());int
method②:
= intObject stoi ()object;int
method③:
= len . objectsize();int
*= intPtr new int []len;for
( int= i 0 ;<= i ; len++ i)*
{
(+intPtr ) i= [ object]i- '0' ;}
Converting Strings to Numbers in C/C++
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)