Search code examples
cdo-whiledigitscs50

Why won't my do while loop stop break?


I am trying to make a do-while loop. I am trying to get the user input as long as the user's input's length of the digit is less than 13 digits long or greater than 16 digits long.

Example:
1234 (4 digits) would run the do while loop again,
123493919295919(14 digits) would stop the loop.

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    int n;
    int nDigits;
    do
    {
        n = get_int("Please enter your credit card number:\n");
        nDigits = floor(log10(abs(n))) + 1;
    }
    while (nDigits < 13 || nDigits > 16);
}

Solution

  • What is int in your system? Is it 4 bytes (32 bits)?

    nDigits for type int, that has 32 bits, will be always less than 11 (I mean that INT_MAX which is equal to 2147483647 gives just 10), so condition is TRUE (because (nDigits < 13 || nDigits > 16) gives true OR false, that is true).

    So consider changing type for data representation.

    Options:

    1. char[17] to store strings up to 16 characters (inside string you can check that all characters are digits, see isdigit)
    2. uint64_t form <stdint.h> (there seems to be no negative card numbers)