1

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?

EdCase
  • 119
  • 2
  • 7
  • 1
    `printf("card number is: %s\n");` you mean `printf("card number is: %s\n", str_number);` else the behavior is undefined because the argument for `%s`is missing – bruno Aug 12 '20 at 13:47
  • 1
    Note also that, if `count` is the number of digits you have, then you will need `count+1` elements in your `str_number` array (space for the null-terminator). – Adrian Mole Aug 12 '20 at 13:48
  • 2
    I do not understand how you can compare *atoi* and *sprintf*, the first extract (poorly) a number from a string and the second does the reverse operation as you use it. Not *sprintf* does not 'convert' but print/write – bruno Aug 12 '20 at 13:49
  • @bruno. Thanks for that, it has compiled now. Now to see if it works (i meant `itoa` :) – EdCase Aug 12 '20 at 13:55
  • @Adrian Mole. Thanks, always forget about the pesky null char – EdCase Aug 12 '20 at 13:56
  • There is std::atoll https://en.cppreference.com/w/cpp/string/byte/atoi – armagedescu Aug 12 '20 at 13:59
  • 3
    This is a well-known CS50 exercise you are working on. For this exercise, it is better to read the card “number” as a string of characters and operate on those, not to read them as a number. – Eric Postpischil Aug 12 '20 at 14:09

1 Answers1

3

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

bruno
  • 32,421
  • 7
  • 25
  • 37