字符串解析通过sscanf

时间:2015-07-13 16:08:21

标签: c++ string scanf

需要初学者C ++代码的帮助:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>

LONG __cdecl main(LONG     Argc, char* Argv[])
{

    if (Argc == 8 && stricmp(Argv[1], "sendir") == 0){

        int nDeviceID;
        unsigned short nUsage, nUsagePage;
        BYTE nIRBlink, nMsgCode, nHidReportID;

        sscanf_s(Argv[2], "%d", &nDeviceID);
        sscanf_s(Argv[3], "%4hhx", &nUsage);
        sscanf_s(Argv[4], "%4hhx", &nUsagePage);
        sscanf_s(Argv[5], "%2hhx", &nHidReportID);
        sscanf_s(Argv[6], "%2hhx", &nIRBlink);
        sscanf_s(Argv[7], "%2hhx", &nMsgCode);

        printf("param: %d, %d, %d, %d, %d, %d\n", nDeviceID, nUsage, nUsagePage, nHidReportID, nIRBlink, nMsgCode);

    }
    return 0;
}

所以我输入cmd提示符: test.exe sendir 2 0001 ff00 06 01 01

我得到了: param:2,1,65280,0,0,1

理想情况下我想要: param:2,1,65280,6,1,1

我认为问题在于我如何使用sscanf ......

2 个答案:

答案 0 :(得分:0)

代码失败使用了错误的scanf说明符。

    int nDeviceID;
    unsigned short nUsage, nUsagePage;
    BYTE nIRBlink, nMsgCode, nHidReportID;

    sscanf_s(Argv[2], "%d", &nDeviceID);

    // Wrong, Use hx with unsigned short than hhx
    sscanf_s(Argv[3], "%4hx", &nUsage);
    sscanf_s(Argv[4], "%4hx", &nUsagePage);

    // Likely OK if BYTE is the same as unsigned char
    sscanf_s(Argv[5], "%2hhx", &nHidReportID);
    sscanf_s(Argv[6], "%2hhx", &nIRBlink);
    sscanf_s(Argv[7], "%2hhx", &nMsgCode);

在所有情况下都未检查sscanf_s()的结果,对转换的成功产生怀疑。

替代方案:使用自己的转换函数Ref

    errno = 0;
    char *endptr; 
    nDeviceID = strtoi(Argv[2], &endptr, 10);
    if (errno || *endptr) Fail();
    nUsage = strtosuchar(Argv[3], &endptr, 16);
    if (errno || *endptr) Fail();
    ...

答案 1 :(得分:-1)

想出来。

    sscanf_s(Argv[2], "%d", &nDeviceID);
    sscanf_s(Argv[3], "%4hhx", &nUsage);
    sscanf_s(Argv[4], "%4hhx", &nUsagePage);
    //sscanf_s(Argv[5], "%2hhx", &nHidReportID);
    nHidReportID = (byte)strtoul(Argv[5], NULL, 16);
    //sscanf_s(Argv[6], "%2hhx", &nIRBlink);
    nIRBlink = (byte)strtoul(Argv[6], NULL, 16);
    //sscanf_s(Argv[7], "%2hhx", &nMsgCode);
    nMsgCode = (byte)strtoul(Argv[7], NULL, 16);

总而言之,不要使用sscanf。