How to convert an int to string in C?

This blog post will teach you how to convert an int to a string in C. The itoa() function (non-standard function) converts an integer value to a null-terminated string using the specified base (behavior depends on implementation).

As itoa() is not a standard function, in my recommendation, it is best to use sprintf() or snprintf()(snprintf safe for buffer overflows).

 

Using the sprintf():

Syntax:

int sprintf(char * restrict str, const char * restrict format, ...);

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument str) rather than to a stream.

Following is an example code to convert an int to string in C.

#include<stdio.h>

int main()
{
    char result[100] = {0};
    int num = 99;

    sprintf(result, "%d", num);

    printf("Converted int to string = %s\n", result);

    return 0;
}

Output: Converted int to string = 99

 

Using the snprintf():

Syntax:

int snprintf(char * restrict str, size_t n, const char * restrict format, ...);

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument str) rather than to a stream.

If n is zero, nothing is written, and str may be a null pointer. Also, the resulting string could not consist of more than n characters including the null character.

#include<stdio.h>

int main()
{
    char result[100] = {0};
    int num = 99;

    snprintf(result, 100,"%d", num);

    printf("Converted int to string = %s\n", result);

    return 0;
}

Output: Converted int to string = 99

 

Using the itoa():

The itoa() is a non-standard function converts an integer value to a null-terminated string using the specified base. It stores the result in the array given by str parameter. But it is my recomendation you should verify your platform before using the itoa().

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


int main()
{
    char result[100] = {0};
    int num = 99;

    //convert an int to string in C
    itoa(num,result,10);

    printf("Converted int to string = %s\n", result);

    return 0;
}

Output: Converted int to string = 99

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *