I am trying to make a server that will take input from the client in postfix notation and send back a result. I have tried a few different things and have ended up using strtok() and strcmp() to find the inputs, but for some reason my server is reading the + symbol as the * symbol.
/* Calculation runs the calculation of the given values */
void calculation (int sock){
int n;
char buffer[BUF_SIZE];
char * n1;
char * n2;
char * sym;
int answer;
bzero(buffer, BUF_SIZE);
n = read(sock,buffer, sizeof(buffer));
if (n < 0) error("ERROR reading from socket");
printf("Here is the desired calculation: %s\n",buffer);
n1 = strtok(buffer, " ");
printf("%s\n", n1);
n2 = strtok(NULL, " ");
printf("%s\n", n2);
sym = strtok(NULL, " ");
printf("%s\n", sym);
int num1 = atoi(n1);
printf("%d\n", num1);
int num2 = atoi(n2);
printf("%d\n", num2);
if(strcmp(sym, "+") == 0){
answer = num1 + num2;
printf("1 %d\n", answer);
}
if(strcmp(sym, "-") == 0){
answer = num1 - num2;
printf("2 %d\n", answer);
}
if(strcmp(sym, "*") == 0){
answer = num1 * num2;
printf("3 %d\n", answer);
}
if(strcmp(sym, "/") == 0){
answer = num1 / num2;
printf("4 %d\n", answer);
}
if(strcmp(sym, "%") == 0){
answer = num1 % num2;
printf("5 %d\n", answer);
}
printf("%d\n", answer);
snprintf(buffer, sizeof(buffer), "The result is: %d", answer);
n = write(sock, buffer, 18);
if (n < 0) error("ERROR writing to socket");
}
(Edit) Thank you for the advice on responses, I am checking the sym and it outputs it as the right symbol, but as was mentioned in the comments has an extra newline. I'm not sure what is causing it. Thank you for any help.
My output when I use the server is:
Here is the desired calculation: 3 4 +
3
4
+
3
4
32669