C++中将string类型转化为int 类型

如果直接用一个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;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是牛大春呀

老板糊涂啊

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值