atoi函数的用法

来源:互联网 发布:人工智能泰迪熊 编辑:程序博客网 时间:2024/05/24 05:21
就自己写写代码(根据atoi()的功能)来表示atoi()函数的实现。我在这里先把atoi()函数的功能贴出来,也好有个参考啊~~~

atoi()函数的功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回(返回转换后的整型数)。

atoi()函数实现的代码:

[cpp] view plaincopyprint?
  1. /*
  2. * name:xif
  3. * coder:xifan@2010@yahoo.cn
  4. * time:08.20.2012
  5. * file_name:my_atoi.c
  6. * function:int my_atoi(char* pstr)
  7. */
  8. int my_atoi(char* pstr)
  9. {
  10. int Ret_Integer = 0;
  11. int Integer_sign = 1;
  12. /*
  13. * 判断指针是否为空
  14. */
  15. if(pstr == NULL)
  16. {
  17. printf("Pointer is NULL\n");
  18. return 0;
  19. }
  20. /*
  21. * 跳过前面的空格字符
  22. */
  23. while(isspace(*pstr) == 0)
  24. {
  25. pstr++;
  26. }
  27. /*
  28. * 判断正负号
  29. * 如果是正号,指针指向下一个字符
  30. * 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符
  31. */
  32. if(*pstr == '-')
  33. {
  34. Integer_sign = -1;
  35. }
  36. if(*pstr == '-' || *pstr =='+')
  37. {
  38. pstr++;
  39. }
  40. /*
  41. * 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer
  42. */
  43. while(*pstr >= '0' && *pstr <='9')
  44. {
  45. Ret_Integer = Ret_Integer * 10 + *pstr - '0';
  46. pstr++;
  47. }
  48. Ret_Integer = Integer_sign * Ret_Integer;
  49. return Ret_Integer;
  50. }

现在贴出运行my_atoi()的结果,定义的主函数为:int main ()

[cpp] view plaincopyprint?
  1. int main()
  2. {
  3. char a[] = "-100";
  4. char b[] = "456";
  5. int c = 0;
  6. int my_atoi(char*);
  7. c = atoi(a) + atoi(b);
  8. printf("atoi(a)=%d\n",atoi(a));
  9. printf("atoi(b)=%d\n",atoi(b));
  10. printf("c = %d\n",c);
  11. return 0;
  12. }

运行结果:


原创粉丝点击