如果直接用一个string 变量 给 int 类型变量赋值,如:
string a="??";
int i =a;
编译器是会直接报错的,报错内容如下:
[Error] cannot convert ‘std::basic_string< char>’ to ‘int’ in initialization
如果像之前的那种类型强制转换呢?
string a="??";
int i =(int )a;
还是不行
报错如下:
[Error] invalid cast from type ‘std::string {aka std::basic_string< char>}’ to type ‘int’
那怎么办呢?
特意查了一下,原来C++中的 string 类中给了相关的函数 用来类型转换.
① to_string 函数
使用方法如下:
double a = 3.14 //或者 int a = 3;
string str=to_string (a);
②stoi() 函数
③atio() 函数
stoi的形参是const string*
atio的形参是const char *
string.c_str 是string类中的一个函数,它返回当前字符串的首字符地址。
因此 c_str函数的返回值是const char*。
所以可以有两种转换方法.
string s1("123");
char* s2 = "123";
int a = stoi(s1);
int b = atoi(s2);
int c = atoi(s1.c_str());
cout << a << endl;
cout << b << endl;
cout << c << endl;