scanf - how do i use sscanf() method in C -


i use sscanf in code

while(totalbyte < sizeof(rdata))  {        read(client_sockfd, &buffer[totalbyte],1);      printf("bytes[%d] : %x \n", totalbyte, buffer[++totalbyte]); } 

use code , got result this

client send 1 1 +

bytes[0] : 0   bytes[1] : 0   bytes[2] : 0   bytes[3] : 1   bytes[4] : 0   bytes[5] : 0 bytes[6] : 0   bytes[7] : 1   bytes[8] : 2b  bytes[9] : 0   bytes[10] : 0   bytes[11] : 0  bytes[12] : 0   bytes[13] : 0   bytes[14] : 0   bytes[15] : 0   bytes[16] : 0   bytes[17] : 0  bytes[18] : 0   bytes[19] : 0  

got result

then use sscanf method

sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);  printf("%d %c %d \n", ntohl(rdata.left_num),rdata.op,ntohl(rdata.right_num)); 

but when print rdata(structure)'s value , 0 value(init value).

0 0

i know sscanf method split string , insert value

is there misunderstood me?

this used structure

struct cal_data  {       int left_num;       int right_num;     char op;       int result;       int error;   };  

i don't think doing want to:

printf("bytes[%d] : %x \n",totalbyte, buffer[++totalbyte]); 

if working, it's working coincidence. don't want rely on coincidence, rather logic, you? read this question more information on undefined behaviour here. change this, , avoid omitting sequence points in order cram logic in future:

printf("bytes[%d] : %x \n",totalbyte, (unsigned int) buffer[totalbyte]); totalbyte++; 

then use sscanf method sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);

where error checking? standard c functions, code should checking return value of sscanf ensure extracted amount of information want. how can sure sscanf processed 2 decimal digit sequences , character? use this:

int n = sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op); if (n == 3) {     /* sscanf extracted , assigned 3 values;      * 1 each of format specifiers,      * , variables passed in. success! */     printf("%d %c %d \n", ntohl(rdata.left_num),rdata.op,ntohl(rdata.right_num)); } else {     /* sscanf failed extract values string,      * because string wasn't correctly formatted */     puts("invalid input sscanf"); } 

... , you'll see problem! sscanf failed!

as others have indicated, string terminates @ first '\0' (or 0) byte. pointer you're passing sscanf points empty string. sscanf can't extract of information want empty string.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -