Your issue is caused by undefined behavior due to improper memory usage:
str_of_evens
→ It contains garbage data, which causes strcat()
to behave unpredictablyatoi()
on a single character → atoi()
expects a null-terminated string, but you're passing a single charactersum_to_str
→ char sum_to_str[3];
is too small for storing two-digit numbers safelyI'm attaching the corrected version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT_LENGTH 255
int main(void) {
char user_input[MAX_INPUT_LENGTH];
char *p;
printf("Welcome to the Credit Card Validator!!\n");
printf("INSTRUCTIONS: At the prompt, please provide a CC number.\n");
char example_card_num[] = "4003600000000014";
int card_num_length = strlen(example_card_num);
int skip_flag = 0;
int sum_of_values = 0;
char value_at_index;
char str_of_evens[20] = {0};
for (int i = card_num_length - 1; i >= 0; i--) {
char sum_to_str[4] = {0};
switch (skip_flag) {
case 0:
value_at_index = example_card_num[i];
sum_of_values += value_at_index - '0';
skip_flag = 1;
break;
case 1:
value_at_index = example_card_num[i];
int multiplied_value = (value_at_index - '0') * 2;
sprintf(sum_to_str, "%d", multiplied_value);
strncat(str_of_evens, sum_to_str, sizeof(str_of_evens) - strlen(str_of_evens) - 1);
skip_flag = 0;
break;
}
}
char value_at_index_two;
for (size_t i = 0; i < strlen(str_of_evens); i++) {
value_at_index_two = str_of_evens[i];
sum_of_values += value_at_index_two - '0';
}
printf("~~~~~~~~~~~\n");
printf("Sum of Values 01: %d\n", sum_of_values);
return 0;
}