Home > OS >  Storing each individual digit from an integer in array
Storing each individual digit from an integer in array

Time:10-24

Good day,

I am quite new to c and trying to find a way to store user integer input into an array as individual digits.

For example,

User input: 2736

I would like it to be stored in array

digits[0] = {2} 
digits[1] = {7} 
digits[2] = {3} 
digits[3] = {6}

I have searched many online discussions but many solutions was to use a for loop and it would not be user friendly if the user is trying to enter a large number for example 209377383838.

Does anyone have a solution to store an input, break it down and store individual number into the array? Thanks for the help!

CodePudding user response:

You can store the number from user as string and then convert from ASCII format to decimal and store it in your array:

#include <stdio.h>
#include <string.h>

int main(){
    char input[1001];
    int arr[1000];
    int i;

    // Take the number as string
    printf("Enter the number: ");
    scanf("%s", input);

    // Convert ASCII to decimal
    for (i = 0; i < strlen(input); i  )
    {
        arr[i] = input[i] - '0';
    }

    return 0;
}

CodePudding user response:

You can use sprintf function to put an integer number to a string.

Note1: As the input is a long int, then can't be more than 2,147,483,647.

Note2 : may be interesting to use unsigned long long int, that Contains at least the [0, 18,446,744,073,709,551,615] range. It's specified since the C99 version of the standard.

int main()
{
long int num; 
scanf("%li",&num);

// Convert number to a string
char snum[20];
sprintf(snum,"%ld", num);

printf("Number as string: %s\n", snum);

return 0;
}

[Update]

If the input can be a string type, then you can use the gets function.

#include <stdio.h>
int main()
{
char snum[20];  
gets(snum);
    // this loop is just to show the result.
    for (int i=0;i<strlen(snum);i  ){
        printf("digits[-] = {%c} \n", i,snum[i]);
    }

return 0;
}

[Input] example: 209377383838

[Output]

digits[ 0] = {2} 
digits[ 1] = {0} 
digits[ 2] = {9} 
digits[ 3] = {3} 
digits[ 4] = {7} 
digits[ 5] = {7} 
digits[ 6] = {3} 
digits[ 7] = {8} 
digits[ 8] = {3} 
digits[ 9] = {8} 
digits[10] = {3} 
digits[11] = {8} 
  • Related