質問

So, I have an input expression which is of the form ....?5+8 ...

I need to parse this and evaluate the result. Since I know that the expression starts after the ? and ends with a ' ', I tried this:

int evaluate(char *buffer){
char exp[50];
while(buffer[i] != '+' || buffer[i] != '-' || buffer[i] != '*' || buffer[i] != '/'){
    exp[j] = buffer[i];
    i++;
    j++;
}
exp[j] = '\0';
int number1 = atoi(exp);

char operation = buffer[i];
i++;
j = 0;
while(buffer[i] !=' '){
    exp[j] = buffer[i];
    i++;
    j++;    
}
exp[j] = '\0';
int number2 = atoi(exp);

 switch(operation)....
 }

where j is initialized from 0 and i is initialized to the position after ?.

The function is called using evaluate(buffer);

However, I keep getting the error Segmentation Fault (core dumped).

EDIT Here's the debugger output

82                              evaluateExp(buffer);
(gdb) next

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401257 in evaluateExp (
buffer=0x603010 "GET /calculate.html?555+777 HTTP/1.1\nHost:localhost\n\n") at webserver.c:108
108             while(buffer[i] != '+' || buffer[i] != '-' || buffer[i] != '*' || buffer[i] != '/'){
(gdb) next

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.

Any Ideas?

役に立ちましたか?

解決

#include <stdio.h>

int evaluate(char *buffer){
    char operation[2];
    int number1, number2;
    sscanf(buffer, "?%d%1[+*/-]%d", &number1, operation, &number2);
    switch(operation[0]){
    case '+':
        return number1 + number2;
    case '-':
        return number1 - number2;
    case '*':
        return number1 * number2;
    case '/':
        return number1 / number2;
    }
}
int main(void){
    char exp[50];
    fgets(exp, sizeof(exp), stdin);
    printf("%d\n", evaluate(exp));
    return 0;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top