温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在C++中将string类型转换成int类型

发布时间:2021-02-22 17:50:36 来源:亿速云 阅读:994 作者:戴恩恩 栏目:编程语言

本文章向大家介绍怎么在C++中将string类型转换成int类型的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

方法一:atoi函数

atoi函数将字符串转化为整数,注意需要stdlib库。所以就尝试了一下:

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
 string a="11",b="22";
 cout<<atoi(a)+atoi(b)<<endl;
 return 0;
}

然而却发现报错:

怎么在C++中将string类型转换成int类型

显然,atoi需要的事const char*类型,而我上面给的上string类型,所以就要 多加一个函数string.c_str()。string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

c_str函数的返回值是const char*,所以我们加上c_str()函数:

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
 string a="11",b="22";
 cout<<atoi(a.c_str())+atoi(b.c_str())<<endl;
 return 0;
}

以上就是小编为大家带来的怎么在C++中将string类型转换成int类型的全部内容了,希望大家多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI