gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:22:43 25 4
gpt4 key购买 nike

我在此代码中使用 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;
};

最佳答案

我认为这没有达到您想要的效果:

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

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

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

then i use sscanf method 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 无法从空字符串中提取任何您想要的信息。

关于c - 如何在 C 中使用 sscanf() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15846203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com