int atoi(const char *nptr);

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

头文件: #include <stdlib.h>

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

 1 #include <iostream>
 2 #include <cctype>
 3 
 4 //参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零
 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("\t    +3543ddd") <<endl << atoi("\n56.34") << endl << atoi("   .44") << endl << atoi("") <<endl
50             << atoi("\t") << endl <<atoi("\o") << endl;
51 
52     cin.get();
53 } 

posted on 2014-08-14 15:20  简单的信仰  阅读(784)  评论(0编辑  收藏  举报