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


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

  方法一:atoi函数

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

  

 1 #include <iostream>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 using namespace std;
 5 int main()
 6 {
 7     string a="11",b="22";
 8     cout<<atoi(a)+atoi(b)<<endl;
 9     return 0;
10 
11 }

  然而却发现报错:

  

  显然,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;

}

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

 

  

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM