【练习题】atoi和itoa函数的实现
2015-06-19 00:08
323 查看
int atoi (const char * str); //Convert string to integer
char * itoa ( int value, char * str, int base ); //Convert integer to string (non-standard function)
#include <stdio.h> #include <ctype.h> int my_atoi(const char *s) { int i =0; int total = 0; int sign; while(isspace(*s)) //跳过空白符 s++; sign = *s; if(*s == '+' || *s == '-') //跳过符号位 { s++; } while(isdigit(*s)) { total = 10*total + (*s - '0'); //将数字字符转换成整形数字 s++; } if(sign == '-') return -total; else return total; } int main(void) { char str[256]; printf ("Enter your a numeric string: "); scanf("%s",str); printf("%d\n",my_atoi(str)); }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> char *my_itoa(int value, char * str, int base) { int sign,ch; int i,len; char *tmp = str; char c; unsigned uvalue; if(base > 36 || base <=1) { printf("Base is between 2 and 36\n"); return 0; } sign = (base == 10 && value < 0); if(sign) //记录符号,使value为正数 uvalue = -value; else uvalue = (unsigned)value; while(uvalue) { ch = uvalue%base; uvalue = uvalue/base; if(ch < 10) *tmp = ch + '0'; // 0-9 直接输出"0"-"9" else *tmp = ch - 10 + 'a'; // > 10 输出"a"-... tmp++; } if(sign) *tmp++ = '-'; *tmp = '\0'; //生成的数字是逆序的,所以要逆序输出 len = strlen(str); for(i=0;i<len/2;i++) //首尾交换,共计 len/2 次 { c = str[i]; str[i] = str[len-i-1]; str[len-i-1] = c; } return str; } int main(void) { int value,base; char str[100]; while(1) { printf("please input a number and base:"); scanf("%d %d",&value,&base); printf("my_itoa:%s\n",my_itoa(value,str,base)); printf("itoa:%s\n",itoa(value,str,base)); } }
相关文章推荐
- android TextView的xml属性一览表
- Linux Shell 学习笔记(三)--Shell变量
- 银子交易
- 2015061810 - 茫茫
- nslookup命令
- Linux Shell 学习笔记(二)
- 开发工具分享
- linux内核 address_space 结构
- Android开发_如何设置按钮背景透明与半透明_图片背景透明
- Linux Shell 学习笔记(一)
- scrapy爬豆瓣电影
- <转>malloc原理和内存碎片
- LeetCode——Min Stack
- 伪数组转为数组 Array.prototype.slice.call(arguments)
- Ubuntu下 vi编写第一个C语言程序
- cdh5.3中配置sparksql
- 大道至简_阅读笔记03
- Lucene知识总结(Query篇)
- 使用OSC52实现iTerm2远程pbcopy
- 在 Linux 中加速工作的键盘快捷键