Crowder Crowder - 2 months ago 5x
C Question

Calling the 1's, 10's, 100's... columns of an integer using a string array

I'm trying to convert a long long integer to a string array with the 1's column in position 0 of the array, the 10's column in position 1, the 100's column in position 2, like this:

INPUT: 4444555566667777 -----> OUTPUT: [4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7]

To test my code, I wrote for my last line

. I expected my program to output the value of position 4, "7". Instead, it output "52". Changing my last line to
yields "53" instead of "6", as I expected. Can anyone explain what's going on?

Surely 52 and 53 correspond to ASCII values, but then, how can I convert them to integers? Can I do this in line?

Where I'm headed with this part of my program is to add up all of the numbers in the 10's, 1,000's, 100,000's, 10,000,000's... columns. Every other digit in a base-10 credit card number. This is one step in my attempt at a Luhn validation.

// Libraries
#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Program
int main(void)
// Get CC number
printf("Enter your credit card number: ");
long long number_ll = GetLongLong();
// printf("%lld\n", number_ll);

// Convert long long to string
char number_str[64];
sprintf(number_str, "%lld", number_ll);
// printf("%s\n", number_str);

// Get length of card number string
int cclength = strlen(number_str);

// Check the length of card number string
if ( ! (cclength == 13 || cclength == 15 || cclength == 16))


Using "%d" on a char will print its ASCII code. Use "%c" to print itself.

And your string's order is reversed compared to your purpose. The rightmost digit(1's column) is at the tail of the string, and the leftmost one is in position 0.

So to print the number at position i (count from right to left), you should use:

printf("%c\n", number_str[cclength - i - 1]);