简体   繁体   中英

C Extract Infix (char array) and cast to int

Given a string/char array eg :

99+(88-77)*(66/(55-44)+33)

How do I extract the numbers and operators?

I would like to store them into two stacks a and b each containing number and operators only.

I am not sure on the logic, I was thinking of scanning each char in the char array, adding the char (number) into another char, until it meets an operator. Then I go to the char(number) and concatenate the string.

Is there a better way to do this, preferabbly without external libraries?

As pointed out in comments, you can try using strtol for scanning integers from input string. I tried the suggested approach and it seemed to work for me for the provided test case. I haven't tested this for corner cases, but this should give you better idea of what users in comments are saying:

int main() {
    char input[30] = "99+(88-77)*(66/(55-44)+33)";
    // Initialize Stack Indices
    operandStackIndex = 0;
    operatorStackIndex = 0;

    // Our markers for strtol()
    char *pStart = input;
    char *pEnd;
    long ret;

    while ((ret = convertStringToLong(pStart, &pEnd, 10)) > 0) {
        operandStack[operandStackIndex++] = ret;
        pStart = pEnd;
        while (isOperator(*pStart)) { // Check whether character it '+','-','/','(',')','*'..
          operatorStack[operatorStackIndex++] = *pStart;
          pStart++;
        }
    }

    printf("Operand Stack:\n");
    for (int i = operandStackIndex - 1; i >= 0; i--) 
        printf("%d\n", operandStack[i]);

    printf("Operator Stack:\n");
    for (int i = operatorStackIndex - 1; i >= 0; i--)
        printf("%c\n", operatorStack[i]);
}

Here is simple implementation for convertStringToLong method(alternative to strtol ):

long convertStringToLong(char* pStart, char** pEnd, int base) {
    long num = 0;
    while (isDigit(*pStart)) {
        num = num * base + (*pStart - '0');
        pStart++;
    }
    *pEnd = pStart;
    return num;
}

When I ran this, I was able to see expected output:

Operand Stack:
33
44
55
66
77
88
99
Operator Stack:
)
+
)
-
(
/
(
*
)
-
(
+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM