2021年1月1日星期五

One line client-server calculator in C

I'm trying to create a one line client-server calculator in C in linux and i'm stuck on something. I've already created a succesful communication between the client and the server and i know how to transmit data between them. My problem lies in the string manipulation process. So the idea is that you run ./server PORTNUMBER and ./client IP PORTNUMBER . The code used for calculating the result lies on the server's side and everything else on the client's side. After executing both of these the user is asked to type a simple calculation like 10+5 or 4*9 etc. The server then calculates the result and it sents it back to the client for display. I chose to approach this using string manipulation(that was my initial thought process). Suppose the user types 10*51. I save that to a string named operation. Then i do if (strchr(operation,'*')) != NULL to get in to the appropriate if statement. I create a variable len1 to count all the characters until i meet * with len1 = strlen(strchr(operation,'*')). I then strncpy this to a new string(with n = len1-1) and then use the atoi function to get the first operand. This seemed to be working fine at first for the first operand(i mean the number before the *). Then i decided to use strrev to turn 10*51 to 15*01 repeat the whole process and then use strrev again to turn 15 to 51 just before saving it as an int. So my idea would look like this:

len1 = strlen(strchr(oper, '*'));  strncpy(operand1string,operation,len1-1);  op1 = atoi(operand1string);  strrev(oper);  len2 = strlen(strchr(oper,'*'));  strncpy(operand2string,operation,len2-1);  strrev(operand2string);  op1 = atoi(operand2string);  

But for some reason this didn't work as expected. Am I on the right path here or should i implement it with another way? Any suggestions would be more than welcome.

https://stackoverflow.com/questions/65533831/one-line-client-server-calculator-in-c January 02, 2021 at 05:24AM

没有评论:

发表评论