I have tried to write a program in C to check Luhn algorithm for credit cards, but it doesn't work. I think I do not have quite clear how getchar()
works, but this program looked sensible to me. Can you tell me what is wrong with it? Thank you in advance for any help with this.
#include <stdio.h>
int main(void) {
char x;
int n, sum, i, c;
sum = 0;
printf("Insert the number of digits: ");
scanf("%d",&n);
printf("Insert the digits: ");
for(i = n; i > 1; i = i - 1){
x = getchar();
if(i%2==0)
if(2*x < 10) sum = sum + 2*x;
else sum = sum + 2*x - 9;
else sum = sum + x;
i = i - 1;
}
c = (9*sum)%10;
x = getchar();
getchar();
if(x == c) printf("Last digit: %d,\nCheck digit: %d,\nMatching",x,c);
else printf("Last digit: %d,\nCheck digit: %d,\nNot Matching",x,c);
}
getchar()
reads one character. Therefore, the x = getchar();
in the loop is not good because
Instead of x = getchar();
, you should do this in the loop:
scanf(" %c", &x); /* ignore whitespace characters (including newline character) and read one character */
x -= '0'; /* convert the character to corresponding integer */