c++类型转换

最近做项目经常遇到c++各个类型的转换,每次都要上网查,因此非常不方便,降低了开发效率,所以总结了一些c++类型转换的方法,我相信这是很多人都经常遇到的,对大家应该很有帮助。

  1. int转string
int x = 1;
std::stringstream ss;
std::string str;
ss<>str;  //str = '1'
  1. string 转int
std::string str = "1234"
int a = atoi(str.c_str()) //a=1234
  1. char* 转string
char *cstr = "char to string";
string s(cstr); //s = "char to string"
  1. string转const char*
string strtoc = "string to char";
const char *p = strtoc.c_str();
const char *t = strtoc.data(); //可以用string.data() 或者string.c_str()
  1. string 转char*
string s1 = "abcdefg";
char *data;
int len = s1.length();
data = (char*)malloc((len + 1)*sizeof(char));
s1.copy(data, len, 0);
cout << data << endl;
  1. string 转char[]
    由于知道string的长度,可以根据length()函数得到,又根据下标直接访问,所以用一个循环赋值就可以了
string pp = "abcdef";
char pc[8];
int i;
for (i = 0; i < pp.length(); i++){
    pc[i] = pp[i];
}
pc[i] = '\0';

最后以一个例子来说明各个转化过程

#include
#include 
#include 
using namespace std;
#define maxn 1000
int main(){
     int n = 0;
     std::stringstream ss;
     string str;
     ss << n;
     ss >> str;
     cout << str<//int 转string

     str = "345";
     int a = atoi(str.c_str());  //string转int
     cout << a << endl;

     char * cstr = "char to string";
     string s(cstr);    //char* 转string
     cout << s << endl;  

     string strtoc = "string to char";
     const char *p = strtoc.c_str();
     const char *t = strtoc.data();  //string转const char*
     cout << p << endl;
     cout << t << endl;

     string pp = "abcdef";
     char pc[8];
     int i;
     for (i = 0; i < pp.length(); i++)
     {
           pc[i] = pp[i];
     }
     pc[i] = '\0';      //string转char[]
     cout << pc << endl;
     system("pause");
     return 0;
}

你可能感兴趣的:(c++学习,c++类型转换)