标签:
一般写小代码时,常常是c和c++不分的,但是有时会遇到类型转换的问题,比如输入 string ,然而处理函数的参数是char*型,之间需要转换。收集一下网上资料,总结一下。因为还没有时间去研究stl源码,暂时先用着吧。
一、string转char*
1、std::string::c_str
Returns a pointer to an array that contains a null-terminated sequence of characters
返回一个数组指针,包含‘\0’的,
例子
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
int main ()
{
std::string str ("Please split this sentence into tokens");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
std::cout<<cstr<<std::endl;
delete[] cstr;
return 0;
}
使用strcpy复制字符串。
char * strcpy ( char * destination, const char * source );
这里面str.c_str()返回的是const char* 类型的。
2、std::string::data
Returns a pointer to an array that contains the same sequence of characters as the characters that make up the value of the string object.
同样返回的是const char* 类型的。
例子
// string::data
#include <iostream>
#include <string>
#include <cstring>
int main ()
{
int length;
std::string str = "Test string";
char* cstr = "Test string";
if ( str.length() == std::strlen(cstr) )
{
std::cout << "str and cstr have the same length.\n";
if ( memcmp (cstr, str.data(), str.length() ) == 0 )
std::cout << "str and cstr have the same content.\n";
}
return 0;
}
二、char* 转string
1、直接复制
string str;
//getline(cin,str);
char * c="test c char to string";
str=c;
2、std::string::assign
Assigns a new value to the string, replacing its current contents.
其中就有将c-string 赋值的情况
string& assign (const char* s);
string str;
//getline(cin,str);
char * c="test c char to string";
str.assign(c);
暂时更新到这,下次遇到再更新
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u010442328/article/details/46829527