如何正确使用sscanf

时间:2016-05-02 21:04:52

标签: arduino scanf

我必须编写一个Arduino函数来查找电话簿中的数字。由于使用sscanf的条件,我的代码不起作用。我做错了什么?

{{1}}

1 个答案:

答案 0 :(得分:0)

*中的%*s表示“不分配”,此类转化规范不计入成功转化的次数。因此,sscanf()调用将始终返回0(除非扫描的字符串为空;然后返回EOF),因为没有活动转换。

删除*,或用合适的号码替换它。如果ADMIN_PHONE_NUMBERchar ADMIN_PHONE_NUMBER[123];,那么您使用的数字应该是(最多)122:%122s - 因为sscanf()在122个字符后写入空值单个“单词”中有122个字符。目前尚不清楚String ADMIN_PHONE_NUMBER;意味着什么 - 因此不能给出更准确的建议。

将代码缩减为接近MCVE(How to create a Minimal, Complete, and Verifiable Example?):

#include <stdio.h>

int main(void)
{
    char buffer[] = "+CPBR: 1,\"690506990\",129,\"ANDROID\"";
    char number[64];

    int n = sscanf(buffer, "+CPBR: %63s", number);
    printf("n = %d: number = [%s]\n", n, number);

    n = sscanf(buffer, "+CPBR: %*d , \" %63[^\"]", number);
    printf("n = %d: number = [%s]\n", n, number);

    return 0;
}

示例输出:

n = 1: number = [1,"690506990",129,"ANDROID"]
n = 1: number = [690506990]

选择您要使用的选项。在sscanf转换规范中我允许使用允许的空格。如果你愿意,你可以不那么自由。