前言:
string和char,char*,int,double之间的相互转换比较常用,现在总结如下。
正文:
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 1、char --> string
char ch = 'a';
string str(1, ch); //字符转字符串可以用string类的构造函数
cout << str << ":" << str.size() << endl;
// 2、char*或char[] --> string
const char* chs = "abcd";
str = chs; // char*转string可直接赋值
cout << str << ":" << str.size() << endl;
char chs2[] = "efgh";
str = chs2;
cout << str << ":" << str.size() << endl;
// 2.1、 string ---> char*
string str = "hahahahaha";
char* p = (char*)str.c_str(); //字符串转字符串指针用函数c_str()
cout << p << endl;
// 3、int/double --> string
int a = 32456;
str = to_string(a); //可以使用全局函数to_string,函数的参数可以是整型和浮点型
cout << str << ":" << str.size() << endl;
double b = 3.141592653;
str = to_string(b);
cout << str << ":" << str.size() << endl;
// 4、string --> int/double
string strint = "1234";
int aa = stoi(strint); //用全局函数stoi,函数名望文生义
cout << aa << endl;
string strdou = "3.141592635";
double bb = stod(strdou); //用全局函数stod
cout << bb << endl;
}