【c 中将string类型转化为int】C++中将string类型转化为int类型

更新时间:2021-06-23    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

写程序需要将string转化为int,所以就探索了一下。

方法一:atoi函数

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

 代码如下

#include <iostream>

#include

#include

usingnamespacestd;

intmain()

{

 string a="11",b="22";

 cout<

 return0;

}

然而却发现报错:

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

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

 代码如下

#include <iostream>

#include

#include

usingnamespacestd;

intmain()

{

 string a="11",b="22";

 cout<

 return0;

}

然后就成功了,有什么不妥的希望大家指出。

本文来源:http://www.bbyears.com/jiaocheng/125538.html