Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

type conversion - Converting integer to string in C without sprintf

It is possible to convert integer to string in C without sprintf?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's a nonstandard function:

char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation

Edit: it seems you want some algorithm to do this. Here's how in base-10:

#include <stdio.h>

#define STRINGIFY(x) #x
#define INTMIN_STR STRINGIFY(INT_MIN)

int main() {
    int anInteger = -13765; // or whatever

    if (anInteger == INT_MIN) { // handle corner case
        puts(INTMIN_STR);
        return 0;
    }

    int flag = 0;
    char str[128] = { 0 }; // large enough for an int even on 64-bit
    int i = 126;
    if (anInteger < 0) {
        flag = 1;
        anInteger = -anInteger;
    }

    while (anInteger != 0) {?
        str[i--] = (anInteger %?10) + '0';
        anInteger /= 10;
    }

    if (flag) str[i--] = '-';

    printf("The number was: %s
", str + i + 1);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...