While storing a credit card number in an integer is a bad idea because it is not an arithmetic object, it is possible to do it by making leading zeros implicit - adding then only at presentation. For example:
printf( "%16.16llu", card_num ) ;
will print 16 digits with leading zeros.
In that case any value less than 10000000000000000 is valid:
#include <stdio.h>
#include <math.h>
int main()
{
unsigned long long card_num = 0 ;
printf( "Enter your Credit/Debit Card Number.\n");
scanf( "%llu", &card_num ) ;
int count = 16 ;
if( card_num > 9999999999999999ULL )
{
count = (int)log10( (double)card_num ) + 1 ;
}
printf("%d\n", count);
printf( "%16.16llu", card_num ) ;
return 0;
}
One issue with the above is that if a number is entered with leading zeros, but more than 16 significant digits, the leading zeros are not counted - the (int)log10( (double)card_num ) + 1
expression yields the number of significant digits. But if you are counting digits for validation, but leading zeros are valid then you need only test card_num <= 10000000000000000ull
- the number of digits is irrelevant.
#include <stdio.h>
#include <stdbool.h>
#define MAX_CARD_NUM 9999999999999999ULL
int main()
{
unsigned long long card_num = 0 ;
bool card_valid = false ;
while( !card_valid )
{
printf( "Enter your Credit/Debit Card Number.\n");
int check = scanf( "%llu", &card_num ) ;
card_valid = (check == 1 && card_num <= MAX_CARD_NUM ) ;
if( !card_valid )
{
printf( "Invalid card number\n" ) ;
}
}
printf( "%16.16llu", card_num ) ;
return 0;
}
However while it is be possible to encode and store a card number in an integer, it does not make much sense for initial entry because you would normally want to check the user had explicitly entered the leading zeroes as they are important security information, and you cannot do that with integer entry. In which case you would do better to enter and validate a string and then if you wish, convert the string to an integer encoding:
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#define CARD_NUM_LEN 16
int main()
{
unsigned long long card_num = 0 ;
bool card_valid = false ;
char card_str[32] ;
while( !card_valid )
{
printf( "Enter your Credit/Debit Card Number.\n");
fgets( card_str, sizeof( card_str) - 1, stdin ) ;
card_valid = true ;
int numlen = 0 ;
for( numlen = 0; card_valid &&
card_str[numlen] != '\0' &&
card_str[numlen] != '\n'; numlen++ )
{
card_valid = isdigit( card_str[numlen] ) && numlen < CARD_NUM_LEN ;
}
card_valid = card_valid && numlen == CARD_NUM_LEN ;
card_str[numlen] = '\0' ;
if( !card_valid )
{
printf( "Invalid card number\n" ) ;
}
}
printf( "String: %s\n", card_str ) ;
// Convert validated string to integer
card_num = strtoull( card_str, NULL, 10 ) ;
// Present the integer version with leading zeros.
printf( "Number: %16.16llu", card_num ) ;
return 0;
}