0

enter image description here

I have the correct output, but Check50 says it's wrong. Anyone have idea why?

if ( checksum % 10 == 0 )
    {
        // AMEX 15 digits; start with 34,37
        if ( (length == 15) && (nd[length]==3) && (nd[length-1]==4 || nd[length-1] ==7))
        {
            printf("AMEX\n");
        }
        // MASTERCARD 16 digits; start with 51-55
        else if ( (length == 16) && (((nd[length]==5) && ( 0 < nd[length-1] || nd[length-1] < 6 )) || ((nd[length-1]==2) && ( nd[length-1]==2 ))))
        {
            printf("MASTERCARD\n");
        }
        // VISA 13 and 16 digits; start with 4
        else if ( ((length == 16) || (length == 13)) && (nd[length]==4) )
        {
            printf("VISA\n");
        }
        else
        {
            printf("INVALID\n");
            return 0;
        }
    }

1 Answer 1

1

If I had to guess, I'd say that your checksum is being calculated incorrectly. You are failing on all cards that have an even number of digits. Are you sure you are calculating the checksum by starting from the end of the number?


Edited answer based on code:

char n_str[16];
sprintf(n_str, "%lld", n);

Your n_str can only hold a maximum string length of 15 (remember that the final char of a string is the Nul char.) So when you sprintf a 16-digit number into it, you end up overwriting memory that you don't have permission to use.

It probably works fine in your IDE because you have lots of empty memory, but the check50 server won't. That's why your AMEX (which is 15 digits) works, but the MC and VISA fail.

5
  • Thank you for answer! The checksum is correct. Look on output with printf checksum ./credit Number: 5555555555554444 checksum: 60 MASTERCARD ./credit Number: 5105105105105100 checksum: 20 MASTERCARD ./credit Number: 4111111111111111 checksum: 30 VISA ./credit Number: 4012888888881881 checksum: 90 VISA Apr 18, 2018 at 16:30
  • Oh sorry, I didn't see your complete screenshot before. Can you post a link to your entire code and I'll take a look.
    – curiouskiwi
    Apr 18, 2018 at 20:43
  • Here is code github.com/Lifeismystery/cs50/blob/master/credit.c Apr 19, 2018 at 13:12
  • @lifeismystery I edited my comment based on your code.
    – curiouskiwi
    Apr 19, 2018 at 22:21
  • Thank you, changed if for char n_str[18]; and it's work now! Apr 20, 2018 at 10:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .