When I run this program my count variable goes only up to 10 for a reason I don't understand and I want it to go up to 16 in order to check if the input from the user is a card number (16 digits).
I dont specifically want to check if it is a card number, I just want to check if it has 16 digits.
void payment() {
int payway;
int cardnum;
int count = 0;
printf("Type 1 if you want to pay with card and have a discount or 2 if you want to pay with cash:\n");
scanf("%d", &payway);
switch (payway) {
case 1:
{
do {
printf("Type your CC number:\n");
scanf("%d", &cardnum);
while (count != 0) {
cardnum = cardnum / 10;
count ;
}
} while (count != 16);
}
break;
}
}
CodePudding user response:
The line
scanf("%d", &cardnum);
will have undefined behavior if the matched number is not representable as an int, i.e. if it is out of range.
An int is only guaranteed to be able to represent numbers from -32767 to 32767, although on most modern platforms, it is able to represent numbers from -2,147,483,648 to 2,147,483,647. Either way, an int will probably not be sufficient to represent a 16-digit number.
However, a long long int (or simply long long) is guaranteed to be able to represent numbers from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807. This is guaranteed to be sufficient to represent any 16-digit number.
Therefore, the simplest solution to your problem would be to change the line
int cardnum;
to
long long cardnum;
and change
scanf("%d", &cardnum);
to:
scanf("%lld", &cardnum);
However, it is generally better so store long numbers such as phone numbers and credit card numbers as strings, even if they consist only of digits. That way, you don't have to worry about the numerical limitations of an int or a long long.
CodePudding user response:
use a string instead of an int value. example:
char c[] = "123";
size_t len = sizeof(c) / sizeof(char);
len--;
so you can store the size of the array in var len.
