MineSweeperGame powered by Java Swing
期中考试题1:MyDate的部分实现

convert int to string in C

Kavinyao posted @ Mar 21, 2010 06:46:41 AM in 学习心得 with tags c string , 3626 阅读

就是栋gg上课提到的那个,觉得自己做得好烦哪~

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/*function declarations*/
void intToStr(int, char*);
void addNegativeSign(char*);

int main(void)
{
    int n;
    printf("Enter an integer (valid range from -2^31 to 2^31 - 1): ");
    scanf("%d",&n);
    /*since 32-bit integer has most 10 digits, we declare the char array with length of 12*/
    /*10 to hold the value, 1 to hold the ending '\0' and the left is optional to minus sign*/
    char str[12];
    intToStr(n,str);
    printf(str);
}

void intToStr(int n, char* s)
{
    int digits = 0;
    int tempInt = n;
    int flag = 0;
    
    /*first, determine whether the number if positive or negative*/
    if(n < 0){
        n = -n;
        flag = 1;
    }
    
    /*sicne an integer has at least 1 digit, we use the do-while loop*/
    do{
        digits++;
        tempInt /= 10;
    }while(tempInt);
    
    /*allocate essential space for characters needed*/
    char* p = (char *)(malloc(sizeof(char) * (digits+((flag)?2:1))));
    
    /*we form the string from the end, which is synchronized to the modulus operation*/
    char* q;
    for(q = p + digits - 1;q >= p;q--){
        tempInt = n % 10;
        *q = (char)(tempInt) + '0';
        n /= 10;
    }
    q = p + digits;
    *q = '\0';/*set the end char for the sake of safety*/
    
    /*if the number is negative, we need to add the negative sign*/
    if(flag){
        addNegativeSign(p);
    }
    
    strcpy(s,p);
    free(p);/*release the space allocated formerly*/
}

/*this function does not do boudary checing!*/
/*but since we had allocated enough space, it is at least safe to call it from the function above*/
void addNegativeSign(char* s){
    char* ss = s;
    while(*ss != '\0') ss++;
    ss++;
    while(ss > s){
        *ss = *(ss-1);
        ss--;
    }
    *s = '-';
}

 

Sit ea quia accusant 说:
Jun 19, 2018 06:25:02 PM

Clutches of the program have been put forward for the success of the people. An amount of the term has been reported for the use of the resumewriters.com review offerings for the people. The color is painted for the regular use of the themes for the individuals.

Emma 说:
Dec 01, 2022 08:35:10 PM

"To convert an int to a string in C, you can use the sprintf function. This function takes a format string and an int as arguments, and returns a string. The format string sell real estate Port Charlotte defines how the int will be converted to a string. For example, the following format string will convert an int to a string with the format ""%d"": sprintf(""%d"", 123); This will return the string ""123"". "


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter