Convert integer to characters in s - C String

C examples for String:String Function

Description

Convert integer to characters in s

Demo Code

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

/* reverse:  reverse string s in place */
void reverse(char s[]){
    int c, i, j;// www. ja  v a 2 s  .  c  o  m

    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

/* itoa:  convert n to characters in s */
void itoa(int n, char s[])
{
    int i, sign;

    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}


int main(){
    char buf[100], buf1[100];
    int n1;

    while (gets_s(buf) != NULL) {
        sscanf(buf, "%d", &n1);
        itoa(n1, buf1);
        if (strcmp(buf, buf1) != 0)
            printf("botch on %s\n", buf);
    }
    return 0;
}

Result


Related Tutorials