-
TYpe Conversion Problem
I am writing a socket network program where the user can enter ADD 4 5 etc SUB 5 3, etc
The user would enter it and it is stored into a char array and then sent to the server, the server needs to take it and convert/split it to string int int perform the function and return the result. For some reason the conversion to int is not working:
(for testing purposed I have the server printing out the three splits of the sting)
here is an example
Client:
ADD 7 6
Server:
ADD Num1: -107 Num2: 007
Here is the server code where the conversion should take place, and suggestions, I thought I had all the converions performed correctly:
Code:
char temp[4];
int temp1, temp2;
n = recv(ns, &buf, sizeof(buf), 0);
sscanf(buf, "%s %d %d",temp, &temp1, &temp2);
if (temp[0] == 'A' && temp[1] == 'D' && temp [2] == 'D')
write (1,"ADD",4);
else if (temp[0] == 'B' && temp[1] == 'Y' && temp[2] == 'E')
exit(0);
// Contine else if for SUB, MUL, DIV...
////////////////////////////
write (1,temp,4);
write(1," Num1: ",7);
sprintf(temp, "%d", temp1);
write (1,temp,4);
write(1," Num2: ",7);
sprintf(temp, "%d", temp2);
write(1,temp,4);
////////////////////////////
send(ns, temp, sizeof(temp), 0);
-
> n = recv(ns, &buf, sizeof(buf), 0);
I could be wrong but do you need the address operator (&) on buf? Maybe just:
Code:
n = recv(ns, buf, sizeof(buf), 0);
> sprintf(temp, "%d", temp1);
> write (1,temp,4);
And when you write out temp after an sprintf(), why not use strlen:
Code:
sprintf(temp, "%d", temp1);
write (1, temp, strlen(temp));
Include <string.h> for strlen.
-
Thanks for the suggestions, but making those changes do not fix the problem :(
-
> char temp[4];
There's no way you're fitting "ADD 7 6" in there.
Even if you make the buffer large, you still need to take care of message fragmentation yourself.
Something like
Code:
while ( n = recv(ns, buf, sizeof(buf)-1, 0) ) > 0 ) {
// append a \0 to make it a proper string
buf[n] = '\0';
// append the received substring to your result
// if the result now contains a unique marker, say a \n
// then you can quit this loop and do your sscanf
}