C语言 C语言中int转字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5242524/
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 07:59:54  来源:igfitidea点击:

Converting int to string in C

c

提问by Shweta

I am using the itoa()function to convert an intinto string, but it is giving an error:

我正在使用该itoa()函数将 an 转换intstring,但它给出了一个错误:

undefined reference to `itoa'
collect2: ld returned 1 exit status

What is the reason? Is there some other way to perform this conversion?

是什么原因?是否有其他方法可以执行此转换?

回答by Edwin Buck

Use snprintf, it is more portable than itoa.

使用起来snprintf,它比itoa.

itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.

itoa 不是标准 C 的一部分,也不是标准 C++ 的一部分;但是,很多编译器和相关的库都支持它。

Example of sprintf

示例 sprintf

char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

Example of snprintf

示例 snprintf

char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);

Both functions are similar to fprintf, but output is written into an array rather than to a stream. The difference between sprintfand snprintfis that snprintfguarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer.

这两个函数都类似于fprintf,但输出被写入一个数组而不是一个流。之间的差sprintfsnprintfsnprintf保证没有通过写入最多可存储在字符的最大数目缓冲区溢出buffer

回答by Mirwise Khan

Before I continue, I must warn you that itoais NOT an ANSI function — it's not a standard C function. You should use sprintfto convert an intinto a string.

在我继续之前,我必须警告你这itoa不是一个 ANSI 函数——它不是一个标准的 C 函数。您应该使用sprintf将 anint转换为字符串。

itoatakes three arguments.

itoa需要三个参数。

  • The first one is the integer to be converted.
  • The second is a pointer to an array of characters - this is where the string is going to be stored. The program may crash if you pass in a char *variable, so you should pass in a normal sized char array and it will work fine.
  • The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use.
  • 第一个是要转换的整数。
  • 第二个是指向字符数组的指针——这是字符串将被存储的地方。如果你传入一个char *变量,程序可能会崩溃,所以你应该传入一个正常大小的 char 数组,它会正常工作。
  • 最后一个不是数组的大小,而是你的数字的基数——基数 10 是你最有可能使用的。

The function returns a pointer to its second argument — where it has stored the converted string.

该函数返回一个指向它的第二个参数的指针——它存储了转换后的字符串。

itoais a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi.

itoa是一个非常有用的函数,它得到了一些编译器的支持——遗憾的是,它不像atoi.

If you still want to use itoa, here is how should you use it. Otherwise, you have another option using sprintf(as long as you want base 8, 10 or 16 output):

如果您仍然想使用itoa,这里是您应该如何使用它。否则,您可以使用另一个选项sprintf(只要您想要以 8、10 或 16 为基数的输出):

char str[5];
printf("15 in binary is %s\n",  itoa(15, str, 2));

回答by user2622016

Use snprintf- it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0parameters. Allocate one character more for null at the end.

使用snprintf- 它是每个编译器中都可用的标准。通过使用NULL, 0参数调用它来查询所需的大小。最后再为 null 分配一个字符。

int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

回答by Shamim Hafiz

Better use sprintf(),

最好使用 sprintf(),

char stringNum[20];
int num=100;
sprintf(stringNum,"%d",num);

回答by Ahmad Sirojuddin

You can make your own itoa, with this function:

您可以itoa使用此功能制作自己的:

void my_utoa(int dataIn, char* bffr, int radix){
int temp_dataIn;
temp_dataIn = dataIn;
int stringLen=1;

while ((int)temp_dataIn/radix != 0){
    temp_dataIn = (int)temp_dataIn/radix;
    stringLen++;
}
//printf("stringLen = %d\n", stringLen);
temp_dataIn = dataIn;
do{
    *(bffr+stringLen-1) = (temp_dataIn%radix)+'0';
    temp_dataIn = (int) temp_dataIn / radix;
}while(stringLen--);}

and this is example:

这是示例:

char buffer[33];
int main(){
  my_utoa(54321, buffer, 10);
  printf(buffer);
  printf("\n");

  my_utoa(13579, buffer, 10);
  printf(buffer);
  printf("\n");
}

回答by ThiefMaster

Usually snprintf()is the way to go:

通常snprintf()是要走的路:

char str[16]; // could be less but i'm too lazy to look for the actual the max length of an integer
snprintf(str, sizeof(str), "%d", your_integer);

回答by mehrdad khosravi

char string[something];
sprintf(string, "%d", 42);

回答by Safayet Ahmed

Similar implementation to Ahmad Sirojuddin but slightly different semantics. From a security perspective, any time a function writes into a string buffer, the function should really "know" the size of the buffer and refuse to write past the end of it. I would guess its a part of the reason you can't find itoa anymore.

与 Ahmad Sirojuddin 的实现类似,但语义略有不同。从安全角度来看,任何时候函数写入字符串缓冲区时,该函数都应该真正“知道”缓冲区的大小并拒绝写入超过它的末尾。我猜这是您再也找不到 itoa 的部分原因。

Also, the following implementation avoids performing the module/devide operation twice.

此外,以下实现避免了两次执行 module/devide 操作。

char *u32todec( uint32_t    value,
                char        *buf,
                int         size)
{
    if(size > 1){
        int i=size-1, offset, bytes;
        buf[i--]='
int main(void)
{
    uint64_t acc;
    uint32_t inc;
    char buf[16];
    size_t bufsize;
    for(acc=0, inc=7; acc<0x100000000; acc+=inc){
        printf("%u: ", (uint32_t)acc);
        for(bufsize=17; bufsize>0; bufsize/=2){
            if(NULL != u32todec((uint32_t)acc, buf, bufsize))
                printf("%s ", buf);
        }
        printf("\n");
        if(acc/inc > 9)
            inc*=7;
    }
    return 0;
}
'; do{ buf[i--]=(value % 10)+'0'; value = value/10; }while((value > 0) && (i>=0)); offset=i+1; if(offset > 0){ bytes=size-i-1; for(i=0;i<bytes;i++) buf[i]=buf[i+offset]; } return buf; }else return NULL; }

The following code both tests the above code and demonstrates its correctness:

下面的代码既测试了上面的代码,也证明了它的正确性:

void itos(int value, char* str, size_t size) {
    snprintf(str, size, "%d", value);
}

回答by Gewure

int someIntToParse;
char resultingString[length(someIntToParse)];

itos(someIntToParse, resultingString, length(someIntToParse));

..works with call by reference. Use it like this e.g.:

..通过引用调用。像这样使用它,例如:

#include <stdlib.h> // for itoa() call
#include <stdio.h>  

int main() {
    int num = 145;
    char buf[5];

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

    // print our string
    printf("%s\n", buf);

    return 0;
}

now resultingStringwill hold your C-'string'.

现在resultingString将持有你的 C-'string'。

回答by Ishu

see this example

看这个例子

##代码##

see this linkhaving other examples.

请参阅此链接,其中包含其他示例。