life02

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  197 随笔 :: 3 文章 :: 37 评论 :: 0 Trackbacks
int  atoi(const  char  *s)
{
      
char  *p  =  s;
      
char  c;
      
int  i  =  0;
      
while(c=*p++)
      
{
            
if(c>='0'  &&  c <='9')
            
{
                  i  
=  i*10  +  (c-'0');
            }

            
else
                  
return  -1;                    //Invalid  string
      }

      
return  i;
}

********************************************************************************************

itoa       把一整数转换为字符串

例程序:

#include 
<ctype.h>
#include 
<stdio.h>
void        itoa (int n,char s[]);
//atoi 函数:将s转换为整形数
int main(void )
{   
int n;
char s[100];

printf(
"Input n:\n");
scanf(
"%d",&n);

          printf(
"the string : \n");
          itoa (n,s);
return 0;
}

void itoa (int n,char s[])
{
int i,j,sign;

if((sign=n)<0)//记录符号
        n=-n;//使n成为正数
          i=0;
do{
        s[i
++]=n%10+'0';//取下一个数字
}
while ((n/=10)>0);//删除该数字

if(sign<0)
        s[i
++]='-';
s[i]
='\0';
for(j=i;j>=0;j--)//生成的数字是逆序的,所以要逆序输出
        printf("%c",s[j]);

}

http://blog.sina.com.cn/s/blog_49d9a0820100f433.html
posted on 2012-02-21 16:37 life02 阅读(569) 评论(0)  编辑 收藏 引用 所属分类: 笔试

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理