Search code examples
cstringlong-longasprintf

How do I convert a long long into a string?


I am creating a program that takes a numerical input from the user as a long long, and then there is some maths involved with individual digits. I think the best way to do this is to convert the long long to a string and then iterate over the various parts.

I have tried using atoi but that did not work, and now i am playing with sprintf as follows...

if (count == 13 || count == 15 || count == 16)
    {
        char str_number[count];
        // Converting long card_number to a string (array of chars)
        sprintf(str_number, "%lld", card_number);
        printf("card number is: %s\n");
        return 0;
    }

This does not work either.

Can anyone set me on the right track please?


Solution

  • In

    printf("card number is: %s\n");
    

    you missed to give str_number in argument, the behavior is undefined, do

    printf("card number is: %s\n", str_number);
    

    Note if your long long are on 64b a string sized 21 if enough because the longer string is for -4611686018427387903 needing 20 characters more the final null character.


    From your remark :

    Whats the best way to convert the long to a string?

    there is no standard lltoa so sprintf family is the right way, note if you are afraid of writing out of the array you can use snprintf