0

I'm trying to implement a function that will parse numbers for a calculator assignment that I have been given. A for loop has been set up that will iterate through each index in the input array which is a arithmetic equation e.g "1+2+3+4+5". I created a function isDigit() that will return true or false if the character is between 0 and 9. This is how I am parsing the numbers. My problem is that the numbers are not being permanently stored in my numbers[] array which I would like to return.

Currently the numbers are being printed to the console with the first cout as "12345" but with the second cout (currently commented) which to check what my returned array stores is an ambiguous hex number. Can someone please help me to return "12345" in numbers[].

int * parseNumbers(char input[])
{
    static int numbers[10];

    for (int i = 0; i < strlen(input); i++)
    {
        if (isDigit(input[i]))
        {
            numbers[i] = input[i] - '0';
            cout << numbers[i];
        }
    }
    //cout << numbers << endl;
    return(numbers);
}

numbers = 1, 2, 3, 4, 5

currently getting numbers = 002D26E8

Justin
  • 9
  • 1
  • Why not simply use a loop to print each element as you did before? That commented-out `cout` isn't going to work, and that number is not "ambiguous". It is the address of the static `int` array. – PaulMcKenzie Apr 22 '19 at 20:08
  • 1
    Also, you probably want a 2nd index else non-integer chars will leave a blank space in the `numbers` array. `numbers[index++] = input[i];` – 001 Apr 22 '19 at 20:09
  • In the 2nd `cout` call, the array [decays into a pointer](https://en.cppreference.com/w/cpp/language/array#Array-to-pointer_decay), which is what `cout` outputs. You have to use a loop to print the individual elements of the array. – zett42 Apr 22 '19 at 20:12
  • @JohnnyMopp thanks I have been able to get rid of the zero values between my numbers by iterating through again and skipping each 2nd number. – Justin Apr 22 '19 at 21:45
  • @PaulMcKenzie so when I return "numbers" and pass it to another function will I be able to perform operations on each number of the array? Thanks – Justin Apr 22 '19 at 21:47

1 Answers1

-1

I think what you're looking for is atoi to convert char to int.

Instead of using numbers[i] = input[i] - '0';

try this:

numbers[i] = atoi(input[i]);

Make sure to have #include <stdlib.h> if not aready added

Reference: http://www.cplusplus.com/reference/cstdlib/atoi/

CloudEmber
  • 99
  • 4
  • `input[i]` is a single character, `atoi` (or improved and also standard function `strtol`) doesn't work on single characters. `input[i] - '0'` is correct. – Ben Voigt Apr 22 '19 at 20:52