简体   繁体   中英

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);
}

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)

You should take the credit card number as a string, not an int.

The cs50 Reference Documentation is pretty clear on that:

get_int() reads a line of text from standard input and returns it as an int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text does not represent such an int, user is prompted to retry. Leading and trailing whitespace is ignored. For simplicity, overflow is not detected. If line can't be read, returns INT_MAX.

As stated by @VolAnd, this terminates in a signed int32 which has always less than 11 digits and could even be negative...

I changed the ints to longs and it works. That is what cs50 wants us to use. Thanks for the help to everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM