0

Taking in input a number and then put every digit into an array, I have, converted it into a string so that I can put it into an array, but then when I use the cast to remake it a int i get the ascii number..

#include <stdio.h>
#include <stdlib.h>

int main(){

    char num_str[64] = {0};
    int num, cifra;

    printf("Write a number: \n");
    scanf("%d", &num);

    int len = snprintf(num_str, 64, "%d", num);
    printf("The length is %d\n", len);

    for(int i = 0; i < len; i++) {
        cifra = (int)(num_str[i]);
        printf("%d \n", cifra);
    }

    return 0;
}
awwww
  • 23
  • 5

1 Answers1

0

convert it from char to int

Test the character for digit and subtract '0'.

for(int i = 0; i < len; i++) {
    int cifra = num_str[i];
    if (cifra >= '0' && cifra <= '9') printf("%d\n", cifra - '0');
    else printf("%c\n", cifra);  // such as '-'
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256