首先看atoi函数:
C语言库函数名: atoi
名字来源:ASCII to integer 的缩写。
原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零,(意思是遇到非数字或结束符就停止)
头文件: #include <stdlib.h>
输入: -123ab;结果为-123;
输入:abc,输出0.
实现:
int atoiOwn(const char *a) { int val=0; bool b_plus=true;//判断符号 switch(*a) //过滤符号 { case '+': a++; break; case '-': a++; b_plus=false; break; default: break; } while(*a>='0'&&*a<='9') //可以用isdigit判断。 { val=val*10+(*a-'0'); a++; } if(!b_plus) val=-val; return val; } int main() { char a[50]; while(scanf("%s",a)!=EOF) { int ret=atoiOwn(a); printf("%d ",ret); } }
char *itoa(int value, char *string, int radix);
char * itoa ( int value, char * str, int base );
Convert integer to string (non-standard function)
Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, valueis always considered unsigned.
str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
A standard-compliant alternative for some cases may be sprintf:
A standard-compliant alternative for some cases may be sprintf:
- sprintf(str,"%d",value) converts to decimal base.
- sprintf(str,"%x",value) converts to hexadecimal base.
- sprintf(str,"%o",value) converts to octal base.
以下的代码只是模拟了部分功能:
#include<stdio.h> void itoa(int value, char *str) { if (value < 0) //如果是负数,则str[0]='-',并把value取反(变成正整数) { str[0] = '-'; value = 0-value; } int i,j; for(i=1; value > 0; i++,value/=10) //从value[1]开始存放value的数字字符,不过是逆序,等下再反序过来 str[i] = value%10+'0'; //将数字加上0的ASCII值(即'0')就得到该数字的ASCII值 for(j=i-1,i=1; j-i>=1; j--,i++) //将数字字符反序存放 { str[i] = str[i]^str[j]; str[j] = str[i]^str[j]; str[i] = str[i]^str[j]; } if(str[0] != '-') //如果不是负数,则需要把数字字符下标左移一位,即减1 { for(i=0; str[i+1]!='