Convert an array of integers/characters to integer

 I had a little difficult problem where I had a string,  a combination of numbers and characters. Here, I want to segregate only the last two numbers. 

Firstly, I explained how to convert the entire array to integers from lines 8 to 19. Remaining part of the post will explain how to segregate the numbers from the char array and store it as integer. 

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

#define DISC_CODE 7

int main()
{
    int discount_amt[DISC_CODE] = {4,5,9,2,1,5,6};
    int i = 0, k = 0;
    
    /* integer range -2,147,483,648 to 2,147,483,647 */
    while (i <= 6) {
        k = 10 * k + discount_amt[i];
        //printf("DEBUG: i %d k %d disc amount %d\n", \\
                 i, k, discount_amt[i]);
        i++;
    }
    
    printf("Array to integer %d\n", k);
    
    char sale_amt[DISC_CODE] = "DTR2P56";
    int amt = 0;
    i = 5;
    k = 0;
    
    while (i <= 6) {
        /* Convert the single character to integer. */
        amt = sale_amt[i] - '0';
        k = 10 * k + amt;
        //printf(" DEBUG: i %d k %d sale amount %c amt %d\n",\\
                 i, k, sale_amt[i], amt);
        i++;
    }
    
    printf("Array to integer %d\n", k);
    
    return 1;
}

Output:

1
2
Array to integer 4592156
Array to integer 56




Comments