How to convert an int to string in C?

后端 未结 10 1918
南方客
南方客 2020-11-22 02:51

How do you convert an int (integer) to a string? I\'m trying to make a function that converts the data of a struct into a string to save it in a fi

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:31

    The short answer is:

    snprintf( str, size, "%d", x );
    

    The longer is: first you need to find out sufficient size. snprintf tells you length if you call it with NULL, 0 as first parameters:

    snprintf( NULL, 0, "%d", x );
    

    Allocate one character more for null-terminator.

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

    If works for every format string, so you can convert float or double to string by using "%g", you can convert int to hex using "%x", and so on.

提交回复
热议问题