Assigning digits to cells in an integer array

This is a discussion on Assigning digits to cells in an integer array within the C Programming forums, part of the General Programming Boards category; So say that I have the number 1234567 taken from the user with scanf. How can I store EACH DIGIT ...

  1. #1
    Banned
    Join Date
    Sep 2006
    Location
    Ontario, Canada
    Posts
    3

    Assigning digits to cells in an integer array

    So say that I have the number 1234567 taken from the user with scanf. How can I store EACH DIGIT of this number into its own cell in an array? My code is as below, and I wanna modify it so that you can enter your SIN number on one line, not number by number.

    Code:
    /*
    Fred Liu's SIN number validation program.
    ICS3M Mr. Creelman period 2
    Tuesday October 10, 2006 9:38 PM
    */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int sin[9], i;
        
        printf("Welcome to Fred's program.\n\nPlease enter your SIN number one by one: ");
        for (i = 0; i < 9; i++) // This and the next line stores The SIN # into integer array sin[9]
            scanf("%d", &sin[i]);
        for (i = 1; i < 8; i+=2) {
            sin[i]*=2; // The 2nd, 4th, 6th, and 8th digits times 2
            if (sin[i] > 9) // Minus 9 if greater than 9
               sin[i]-=9;
        }
        if ((sin[1] + sin[3] + sin[5] + sin[7] + sin[0] + sin[2] + sin[4] + sin[6] + sin[8]) % 10 == 0) // This is steps b-e
           printf("This SIN number is valid.");
        else
            printf("This is a fake SIN number. The government SWAT team has now been dispatched.");
    
        printf("\n\n");
        system("pause");
        return(0);
    }

  2. #2
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    Read user input as a string using fgets(). Parse the input to make sure that it is numeric, how many digits are in it etc. If it passes parsing, you can extract each character and turn it into a number to store in your array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. convert 32 bit number to array of digits
    By droseman in forum C Programming
    Replies: 11
    Last Post: 02-18-2009, 08:37 AM
  2. No Match For Operator+ ???????
    By Paul22000 in forum C++ Programming
    Replies: 24
    Last Post: 05-14-2008, 10:53 AM
  3. Representing a Large Integer with an Array
    By random_accident in forum C++ Programming
    Replies: 3
    Last Post: 03-03-2005, 11:23 AM
  4. String To Integer Array!!!!
    By Unregistered in forum C Programming
    Replies: 8
    Last Post: 10-29-2001, 09:15 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21