zoukankan      html  css  js  c++  java
  • atoi 实现

    int atoi(const char *nptr);

    把字符串转换成整型数。ASCII to integer 的缩写。

    头文件: #include <stdlib.h>

    参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零,

     1 #include <iostream>
     2 #include <cctype>
     3 
     4 //参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零
     5 int atoi(const char *nptr)
     6 {
     7     if (!nptr)        //空字符串
     8         return 0;
     9 
    10     int p = 0;
    11     while(isspace(nptr[p]))        //清除空白字符
    12         p++;
    13     
    14     if (isdigit(nptr[p]) || '+' == nptr[p] || '-' == nptr[p])        //清除后第一个是数字相关
    15     {
    16         int res = 0;
    17         bool flag = true;        //正负数标志
    18 
    19         //对第一个数字相关字符的处理
    20         if('-' == nptr[p])
    21             flag = false;
    22         else if('+' != nptr[p])
    23             res = nptr[p] - '0';
    24 
    25         //处理剩下的
    26         p++;
    27         while(isdigit(nptr[p]))
    28         {
    29             res = res * 10 + (nptr[p] - '0');
    30             p++;
    31         }
    32 
    33         if(!flag)            //负数
    34             res = 0 - res;
    35         return res;
    36     } 
    37     else
    38     {
    39         return 0;
    40     }
    41 }
    42 int main() 
    43 { 
    44     using std::cin;
    45     using std::cout;
    46     using std::endl;
    47 
    48     cout << atoi("213") <<endl << atoi("+2134") << endl << atoi("-342") <<endl << atoi("   -45d") << endl
    49             <<atoi("	    +3543ddd") <<endl << atoi("
    56.34") << endl << atoi("   .44") << endl << atoi("") <<endl
    50             << atoi("	") << endl <<atoi("o") << endl;
    51 
    52     cin.get();
    53 } 

  • 相关阅读:
    技术的那些事儿_2_产品与工艺
    for与foreach再探讨
    技术的那些事儿_3_西方技术管理的精髓
    搭建免费的.Net开发环境
    CDN
    servu 系统服务看门狗,自动脱机补丁,自动启动
    .NET Remoting程序开发入门篇
    网管必知远程终端3389端口合理修改秘藉
    反射方法调用时的一个错误:参数计数不匹配( parameter count mismatch )
    VPS性能测试第一步:CPU测试
  • 原文地址:https://www.cnblogs.com/jiayith/p/3912629.html
Copyright © 2011-2022 走看看