易百教程

编写程序将整数转换为字符串

定义一个函数以返回整数的字符串表示形式。整数作为参数传递。例如,如果参数为25,则函数将返回:"25"。如果参数是-98,则函数将返回"-98"

实现代码

#include <stdio.h>
#include <stdbool.h>

#define STR_LEN 6                         // 存储值字符串的字符串长度

char* itoa(int n, char str[], size_t size) {
    size_t i = 0;                           // character count
    bool negative = n < 0;                  // Indicates negative integer 
    int length = 0;                         // Length of string
    char temp = '0';                        // Temporary storage

    if (negative)                            // If it's negative...
        n = -n;                               // make it positive

// Generate digit characters in reverse order
    do
    {
        if (size == i + 1 + (negative ? 1 : 0))
        {
            printf("String not long enough.\n");
            return NULL;
        }
        str[i++] = '0' + n % 10;         // Create a rightmost digit
        n /= 10;                         // Remove the digit
    } while (n > 0);                     // Go again if there's more digits

    if (negative)                        // If it was negative...
        str[i++] = '-';                  // ...append minus

    str[i] = '\0';                       // Append terminator
    length = i;                          // Save the length including null character

                       // Now reverse the string in place by switching first and last,
                       // second and last but one, third and last but two, etc.
    for (i = 0; i < length / 2; ++i)
    {
        temp = str[i];
        str[i] = str[length - i - 1];
        str[length - i - 1] = temp;
    }
    return str; // Return the string
}
int main(void)
{
    char str[STR_LEN]; // 存储整数的字符串表示形式
    long testdata[] = { 3L, -98L, 110L, -1L, 999L, -12345L, 12345L };

    for (int i = 0; i < sizeof testdata / sizeof(long); ++i)
    {
        if (itoa(testdata[i], str, sizeof(str)))
            printf("Integer value is %d, string is %s\n", testdata[i], str);
    }
    system("pause");
    return 0;
}

执行上面示例代码,得到以下结果:

Integer value is 3, string is 3
Integer value is -98, string is -98
Integer value is 110, string is 110
Integer value is -1, string is -1
Integer value is 999, string is 999
String not long enough.
Integer value is 12345, string is 12345