How to use the itoa() and sprintf() functions?

The itoa() function is used to convert an integer to a string, with the following prototype:

char* itoa(int value, char* str, int base);

Among them, value is the integer to be converted, str is the string where the conversion result is stored, and base is the numerical system (such as decimal, hexadecimal, etc.).

Example usage:

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

int main() {
    int num = 12345;
    char str[10];

    itoa(num, str, 10); // 将整数num转换为10进制字符串
    printf("str: %s\n", str);

    return 0;
}

The sprintf() function is used to write formatted data into a string, and its prototype is as follows:

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

In this case, ‘str’ is the string used to store the output result, ‘format’ is the formatting string, and ‘…’ is the variable parameter list.

Example Usage:

#include <stdio.h>

int main() {
    int num = 12345;
    char str[10];

    sprintf(str, "%d", num); // 将整数num格式化为字符串
    printf("str: %s\n", str);

    return 0;
}

Either of the two functions can be used to convert an integer into a string, so you can choose the one that best suits your needs.

bannerAds