0

I'm getting positive integers from users.
I used a do-while loop to check and validate that the user input is:

1. A positive integer.
2. The length (I.e size) is between 13 and 16 digits BUT NOT EXACTLY 14-digits.

Everything seems to work , except that when the user enters a 14-digit number the program will accept it instead of REJECTING.

Tia

My code bellow:

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

int main(void)
{
  long CN, min_no_digits, max_no_digits, off_digits;
  do
  {
      min_no_digits = 9999999999999; // 13 digits
      max_no_digits = 9999999999999999; // 16 digits
      off_digits = 99999999999999; // 14 digits

    // below code prompt user for a number abd store it
     CN = get_long("Enter your card nummber: ");
      //below code checks if user entered integer min. of 15 or max. of 16 diguts 
  }
  while (CN < 0 || CN < min_no_digits || CN > max_no_digits || CN == off_digits);

  printf("%li \n", CN);

}

ASIDE QUESTION
Is the a better and faster way of setting the length of integers (min or max length) apart from using something like 9999999999999 as I did in the program code above?

0

A couple of flaws here. First of all, CN == off_digits only checks to see whether the two numbers are the same, i.e., 99999999999999. It doesn't compare the number of digits. So, if CN is 99999999999991, it won't return true and the loop ends.

Second, by the same logic, if the number actually equals min_no_digits or max_no_digits, it will accept the numbers when it shouldn't.

BTW, what happens if the cc number has leading zeros????

A better technique would be to count the number of digits and go from there. You can also capture the digits as you go and process other conditions along the way.

1
  • Thanks, I think I now understand how this program logic really works. I will now use a loop and a counter variable to count the no of digits entered and then compared this with the expected no of digits. Hopes it works and I'll update it here. – KeleosWilliam Dec 25 '19 at 15:25

You must log in to answer this question.

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