20140603 整型转化为字符串 字符串转化为整数

1、整型转化为字符串

整数+'0’隐性转化为char类型的数

void main()
{
    int aa=1;
    char t=1+'0';
    printf("%d\n",t);
    printf("%c\n",t);
}

image

#include<stdio.h>

void main()
{
    int n=12345;
    int i=0;
    int j=0;
    char temp[6];
    char temp1[6];
    while(n!=0)
    {
        temp[i]=n%10+'0';
        n=n/10;
        i++;
    }
    //temp='0';这句话是错的,
    temp[i]=NULL;//temp='\0'
    i--;
    while(i>=0)
    {
        temp1[j]=temp[i];
        j++;
        i--;
    }
    temp1[j]=NULL;
    printf("%s\n",temp1);
}

2、字符串转化为整数

#include<stdio.h>
#include<string.h>
void main()
{
    char string[7]="123456";
    int len=strlen(string);
    int i=0;
    int sum=0;
    while(i<len)
    {
        sum=sum*10+(string[i]-'0');
        i++;
    }
    printf("%d",sum);
}

3、字符串拷贝函数

#include<stdio.h>
#include<malloc.h>
char *strcpy1(char *strDest, const char *strSrc)
{
    if(strSrc==NULL||strDest==NULL)
        printf("拷贝失败\n");
   //assert(strSrc!=NULL&&strDest!=NULL);        
    char *temp=strDest;
    while((*strSrc)!='\0')
    {
        *temp=*strSrc;
        temp++;
        strSrc++;
    }
    *temp='\0';
    return strDest;
}

void main()
{
    char *s="1234";
    char *ss=(char*)malloc(sizeof(char *));
    strcpy1(ss,s);
    printf("%s",ss);
}
posted @ 2014-06-03 19:56  yexuannan  阅读(225)  评论(0)    收藏  举报