C ++中如何将字符串类型转换为int类型?

C ++中如何将字符串类型转换为int类型?

编码文章call10242025-03-09 15:58:5922A+A-

首先提出解决方案:

  • 阿托伊
  • 斯特罗
  • 斯托

这几个有什么不同呢?下面测试对比。

C语言风格函数

atoi与strtol对比:

字符串str = “ 16s ” ;
int a = atoi(str.c_str());
int b = strtol(str.c_str(),nullptr,10);

输出:

atoi的结果为:16
strtol的结果为:16

这两个函数都是从字符串开始寻找数字或正负号或小数点,遇到非法字符终止。

所以到上述s字符就不输出了,提前结束,依次当你的字符串不是数字的时候,或者小数点等非数字,不会报异常!直接输出0。

例如:

字符串str = “ asdsa ” ;
int a = atoi(str.c_str());
int b = strtol(str.c_str(),nullptr,10);

输出:

0
0

strtol标度与atoi来说,支持多种二进制转换,例如8二进制等

例如:

int b = strtol(str.c_str(), nullptr, 8);

C ++风格

在C ++中可以使用stoi来转int,这个函数引用于前两个一个最大特点是:异常!

我们知道C ++引用于C语言多了异常,这也是这个函数在C ++中具有的最显著功能。

例如:

字符串str1 = “ asq,” ;
//     int c = stoi(str1); //报异常 
string str2 = “ 12312 ” ;
int c = stoi(str2);     // ok 
cout << c << endl;

异常如下:

terminate called after throwing an instance of 'std::invalid_argument'
what():  stoi

自定义


如下:

int  stringToInt(const string&s){
     int v;
    串流ss;
    ss << s ss>> v;
    返回 v;
}
int  main(){
     int i = stringToInt(“ 2.3 ”);
    cout << i << endl;
}
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4