自己实现c语言itoa函数_在C / C ++中实现itoa()函数

本文介绍了如何在C/C++中实现itoa()函数,该函数将整数转换为以空值结尾的字符串。由于itoa()并非C标准的一部分,故大多数编译器不支持。文中详细讲解了itoa()的基本语法,并提供了从左至右评估数字的实现方法,包括处理正负整数的情况。最后,给出了实现itoa()函数的完整程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己实现c语言itoa函数

In this article, we’ll take a look at implementing the itoa() function in C/C++.

在本文中,我们将介绍如何在C / C ++中实现itoa()函数。

This is a useful utility function which converts an integer into a null-terminated string.

这是一个有用的实用程序函数,它将整数转换为以空值结尾的字符串。

However, it isn’t supported natively by most compilers, as it is not a part of the C standard.

但是,大多数编译器本身都不支持它,因为它不是C标准的一部分。

Therefore, let’s take a look at using this function, by implementing it ourselves!.

因此,让我们来看看如何通过自己实现此功能!

C / C ++中itoa()函数的基本语法 (Basic Syntax of the itoa() function in C/C++)

While this function may be available in some compilers, there is no function as such, in most of them.

尽管此功能在某些编译器中可用,但在大多数编译器中都没有这样的功能。

The itoa() function takes in an integer num, and stores it into buffer. It also has an optional parameter base, which converts it into the appropriate base.

itoa()函数接受一个整数num ,并将其存储到buffer 。 它还具有一个可选的参数base ,它将其转换为适当的基数。

By default, base is set to 10 (decimal base).

默认情况下, base设置为10(十进制基数)。

After populating buffer, it returns a pointer to the first character of buffer, if the conversion is successful. Otherwise, it returns NULL.

填充buffer之后,如果转换成功,它将返回一个指向buffer的第一个字符的指针。 否则,它返回NULL


char* itoa(int num, char* buffer, int base)

Since there isn’t any default itoa() function in most common C compilers, let’s implement it!

由于在大多数常见的C编译器中没有默认的itoa()函数,因此让我们实现它!



在C / C ++中实现itoa()函数 (Implementing the itoa() function in C / C++)

We’ll take a number, and convert it to a string. We’ll consider both positive and negative integers, and see how itoa() handles them.

我们将取一个数字,并将其转换为字符串。 我们将同时考虑正整数和负整数,并查看itoa()如何处理它们。

Although some websites may have implemented itoa() by evaluating the digits from right to left and then reversing the string, we’ll use a different approach. t

尽管某些网站可能已经通过从右到左评估数字然后反转字符串来实现itoa() ,但我们将使用另一种方法。 Ť

We’ll evaluate the digits from left to right, with the help of certain function from the <math.h> library.

<math.h>库中的某些功能的帮助下,我们将从左至右评估数字。

We’ll follow the below procedure:

我们将遵循以下过程:

  • Find the number of digits of num. If num is positive, we know that the number of digits will be floor(log(num, base)) + 1. (Hint: This is pretty easy to derive using logarithms).

    查找num的位数。 如果num为正数,我们知道位数为floor(log(num, base)) + 1 。 (提示:使用对数很容易得出)。
  • If num is negative, we will only consider the case where base = 10, since we may need to use separate algorithms to evaluate for any base. We need to put the minus sign as the first digit!

    如果num为负,我们将仅考虑base = 10的情况,因为我们可能需要使用单独的算法来评估任何基数。 我们需要将减号放在第一位!
  • Start from the leftmost (highest) digit of num, and keep adding the value to the buffer.

    num的最左(最高)位开始,然后继续将值添加到缓冲区中。

The complete program is shown below. You may be able to understand this better by reading through the code!

完整的程序如下所示。 通过阅读代码,您也许可以更好地理解这一点!


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

char* itoa(int num, char* buffer, int base) {
    int curr = 0;

    if (num == 0) {
        // Base case
        buffer[curr++] = '0';
        buffer[curr] = '\0';
        return buffer;
    }

    int num_digits = 0;

    if (num < 0) {
        if (base == 10) {
            num_digits ++;
            buffer[curr] = '-';
            curr ++;
            // Make it positive and finally add the minus sign
            num *= -1;
        }
        else
            // Unsupported base. Return NULL
            return NULL;
    }

    num_digits += (int)floor(log(num) / log(base)) + 1;

    // Go through the digits one by one
    // from left to right
    while (curr < num_digits) {
        // Get the base value. For example, 10^2 = 1000, for the third digit
        int base_val = (int) pow(base, num_digits-1-curr);

        // Get the numerical value
        int num_val = num / base_val;

        char value = num_val + '0';
        buffer[curr] = value;

        curr ++;
        num -= base_val * num_val;
    }
    buffer[curr] = '\0';
    return buffer;
}

int main() {
    int a = 1234;
    char buffer[256];
    if (itoa(a, buffer, 10) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer);
    }
    int b = -231;
    if (itoa(b, buffer, 10) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer);
    }
    int c = 10;
    if (itoa(c, buffer, 2) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer);
    }
    return 0;
}

Output

输出量


Input = 1234, base = 10, Buffer = 1234
Input = -231, base = 10, Buffer = -231
Input = 10, base = 2, Buffer = 1010

NOTE: If you’re compiling with gcc, use the -lm flag to include the math library.

注意 :如果使用gcc ,请使用-lm标志包括数学库。


gcc -o test.out test.c -lm

Indeed, we were able to get it working. Not only did this work for integers, but only for other bases too!

确实,我们能够使其正常运行。 这不仅适用于整数,还适用于其他基数!



结论 (Conclusion)

Hopefully you were able to get an understanding to converting integers to strings using itoa(), and possibly even implemented one yourself, using this guide!

希望您能够理解使用itoa()将整数转换为字符串的方法,甚至可以使用本指南自己实现!

For similar content, do go through our tutorial section on C programming

对于类似的内容,请阅读我们有关C编程的教程部分



翻译自: https://www.journaldev.com/40684/itoa-function-c-plus-plus

自己实现c语言itoa函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值