zoukankan      html  css  js  c++  java
  • atoi()和stoi()的区别----数字字符串的处理

    相同点:

    ①都是C++的字符处理函数,把数字字符串转换成int输出

    ②头文件都是#include<cstring>

    不同点:

    ①atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char*类型的,而stoi()的参数是const string*,不需要转化为 const char*;

    如图:

    ②stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!

    如图:

     

    而atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;

    代码:

    1. //myfirst.cpp--displays a message
    2. #include "stdafx.h"
    3. #include <iostream>
    4. #include <set>
    5. #include <string>
    6. using namespace std;
    7. int main()
    8. {
    9. string s1 = "2147482", s2 = "-214748";
    10. string s3 = "214748666666663", s4 = "-21474836488";
    11. cout << stoi(s1) << endl;
    12. cout << stoi(s2) << endl;
    13. cout << atoi(s3.c_str()) << endl;
    14. cout << atoi(s4.c_str()) << endl;
    15. return 0;
    16. }

    控制台:

    无欲则刚 关心则乱
  • 相关阅读:
    MOS
    1- Bluetooth开发
    1- Bluetooth
    MCU 51-10 Infrared Communication
    1- STM32 HAL库学习 GPIO配置点亮LED灯
    MCU 51-9 DS18B20 Temperature Sensor
    MCU 51-8 AD/DA
    C语言讲义——变量(variable)
    C语言讲义——注释
    C语言讲义——“编译、链接”
  • 原文地址:https://www.cnblogs.com/xjyxp/p/11451275.html
Copyright © 2011-2022 走看看