我如何在C中使用sscanf()方法

时间:2013-04-06 02:00:00

标签: c scanf

我在这段代码中使用了sscanf

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

使用此代码,我得到了这样的结果

客户端发送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 

得到了结果

然后我使用sscanf方法

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));

但是当打印rdata(结构)的值时,得到一个0值(初始值)。

0 0

我知道sscanf方法拆分一个字符串并插入一个值

有没有人误解我?

这就是我使用的结构

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

3 个答案:

答案 0 :(得分:3)

我认为这不符合您的要求:

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

如果有效,那么巧合。你不想依靠巧合而不是逻辑,对吗?有关未定义行为的更多信息,请阅读this question。将其更改为此,并避免省略序列点,以便将来将逻辑加在一起:

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

然后我使用sscanf方法   sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);

您的错误检查在哪里?与大多数标准C函数一样,您的代码应该检查sscanf的返回值,以确保它提取了您想要的信息量。你怎么能确定sscanf成功处理了两个十进制数字序列和一个字符?使用此:

int n = sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);
if (n == 3) {
    /* sscanf extracted and assigned three values;
     * One for each of the format specifiers,
     * and variables you passed in. Success! */
    printf("%d %c %d \n", ntohl(rdata.left_num),rdata.op,ntohl(rdata.right_num));
}
else {
    /* sscanf failed to extract some values from the string,
     * because the string wasn't correctly formatted */
    puts("Invalid input to sscanf");
}

......现在你会看到问题! sscanf失败了!

正如其他人所指出的,字符串终止于第一个'\0'(或0)字节。您传递给sscanf的指针指向空字符串。 sscanf无法从空字符串中提取您想要的任何信息。

答案 1 :(得分:2)

像许多其他C库函数一样,

sscanf在字符串达到0时停止迭代(与'\ 0'相同)。 bytes数组的第一个元素是0.因此,就sscanf而言,用于sscanf的输入字符串是""。要查看此行为的另一个示例,请在while循环后添加以下代码。

printf("%s\n", bytes);

这不会打印任何内容(会打印一个空字符串),因为像printf这样的sscanf会将byte[0]视为字符串的结尾。

您应该使用类似的内容将数据读入您的结构 - http://c-faq.com/stdio/extconform.html

答案 2 :(得分:1)

根据功能描述(http://www.cplusplus.com/reference/cstdio/sscanf/):

int sscanf ( const char * s, const char * format, ...);

第一个参数应该是:

C string that the function processes as its source to retrieve the data.

但是当你将每个字节打印为“十六进制整数”时:

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

第一个字节的值为0.因此,如果将其视为字符串,则为空字符串。

相关问题