C语言 如何使用 C 将整数转换为字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14564813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:11:08  来源:igfitidea点击:

How to Convert Integer to Character Array using C

c

提问by tousif

I want to convert integer number to character array in C.

我想在 C 中将整数转换为字符数组。

Input:

输入:

int num = 221234;

Result is equivalent to:

结果相当于:

char arr[6];
arr[0] = '2';
arr[1] = '2';
arr[2] = '1';
arr[3] = '2';
arr[4] = '3';
arr[5] = '4';

How can I do this?

我怎样才能做到这一点?

采纳答案by Ravindra Bagale

make use of log10function to determine the number of digits & do like below

使用log10函数来确定数字的数量并像下面这样

char * toArray(int number)
    {
        int n = log10(number) + 1;
        int i;
      char *numberArray = calloc(n, sizeof(char));
        for ( i = 0; i < n; ++i, number /= 10 )
        {
            numberArray[i] = number % 10;
        }
        return numberArray;
    }

or the other option is sprintf(yourCharArray,"%ld", intNumber);

或者另一种选择是 sprintf(yourCharArray,"%ld", intNumber);

回答by Amit Yaron

'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:

' sprintf' 可以正常工作,如果您的第一个参数是指向字符的指针(指向字符的指针是 'c' 中的数组),则必须确保有足够的空间容纳所有数字和终止'\0'。例如,如果一个整数使用 32 位,则它最多有 10 个十进制数字。所以你的代码应该是这样的:

int i;
char s[11]; 
...
sprintf(s,"%ld", i);

回答by PearsonArtPhoto

Use itoa, as is shown here.

使用itoa,如图所示这里

char buf[5];
// convert 123 to string [buf]
itoa(123, buf, 10);

buf will be a string array as you documented. You might need to increase the size of the buffer.

buf 将是您记录的字符串数组。您可能需要增加缓冲区的大小。

回答by John Bode

The easyway is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintfgives you formatting options that itoadoesn't.

简单的方法是使用sprintf。我知道其他人已经建议了itoa,但是 a) 它不是标准库的一部分,并且 b)sprintf为您提供了itoa不属于的格式选项。

回答by Ivaylo Strandjev

You may give a shot at using itoa. Another alternative is to use sprintf.

您可以尝试使用itoa。另一种选择是使用sprintf