-3

I have to input a five digit card # I tried this but realized 00000 wouldn't work

if(credit_card_number > 99999)
          {
             cout << "CREDIT CARD NOT VALID TRY AGAIN TO MANY DIGITS\n";
             credit_card_valid = 0;
          }
          else if(credit_card_number < 10000)
          {
             cout << "CREDIT CARD NOT VALID TRY AGAIN NOT ENOUGH DIGITS\n";
             credit_card_valid = 0;

how would I make it where 00000 through 09999 is a valid card #

Kyle Walls
  • 13
  • 1
  • 1
    Possible duplicate of [Efficient way to determine number of digits in an integer](http://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer) – djechlin Jan 29 '16 at 19:49
  • 2
    00000 (or anything else starting with a 0) isn't an integer, so `credit_card_number` can't be an int. – JJJ Jan 29 '16 at 19:53
  • @Juhana how would i make it 00000 a valid option make it a string? – Kyle Walls Jan 29 '16 at 19:55
  • 3
    You'll have to make it a string and check that it has exactly 5 characters and contains only numbers. – JJJ Jan 29 '16 at 19:55
  • @Juhana Octal numeric literals start with 0. Of course, octal won't solve the OP's issue. – PaulMcKenzie Jan 29 '16 at 19:56
  • @Juhana Thanks ill try that – Kyle Walls Jan 29 '16 at 19:56
  • @Paul Only in certain programming languages, not in the real world. – Alan Stokes Jan 29 '16 at 19:59
  • Well, just to inform the OP that code *could* compile if they had integer literals starting with 0, but the code would not work as the OP would have expected. – PaulMcKenzie Jan 29 '16 at 20:01
  • Since you do not need to do arithmetic operations on that number and you need to keep front zeros, you should not use integral type like `int`, but `std::string` instead and use regular expressions or other string methods to validate – Slava Jan 29 '16 at 21:37

2 Answers2

0

Input your credit card number as a string (look up std::string in the standard header <string>. Then check if it is in the required format.

Since a real credit card number is represented using a set of integer values (notionally separated by spaces), this will work.

To check if a grouping of five characters is all digits, simply check it has length 5, then check if each individual character in that grouping is a digit. Look up std::isdigit() in either <cctype> or (more advanced) <locale>) - those two headers provide different overloads, for use in different contexts.

Peter
  • 35,646
  • 4
  • 32
  • 74
0

Here valid will be equal to 1 if the string contain 5 digits.

std :: string num = "00000";

int valid = num.size() == 5 and 
        std :: all_of(num.cbegin(), num.cend(), [](const char c){ return isdigit(c); });

printf("%d", valid); // 1