Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to GUID with sscanf [closed]

Tags:

c++

c

guid

scanf

I'm trying to convert a string to GUID with sscanf:

GUID guid;
sscanf( "11111111-2222-3333-4455-667788995511", "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
        &guid.Data1, &guid.Data2, &guid.Data3,
        &guid.Data4[0], &guid.Data4[1], &guid.Data4[2],
        &guid.Data4[3], &guid.Data4[4], &guid.Data4[5],
        &guid.Data4[6], &guid.Data4[7]);

However, in runtime, it fails and exits with "Error: Command failed". Why? How to fix it?

I do not want to compile with /clr so cannot use System.

like image 574
Andy Li Avatar asked May 13 '10 04:05

Andy Li


2 Answers

I think you are damaging the stack. X type specifier requires pointer to int which is at least 4 bytes, so starting from &guid.Data[4] parameter you've screwed up. Provide enough space for sscanf and you should be fine. Final code looks like this:

    GUID guid;

    unsigned long p0;
    int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;

    int err = sscanf_s(s.c_str(), "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
        &p0, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10);

    guid.Data1 = p0;
    guid.Data2 = p1;
    guid.Data3 = p2;
    guid.Data4[0] = p3;
    guid.Data4[1] = p4;
    guid.Data4[2] = p5;
    guid.Data4[3] = p6;
    guid.Data4[4] = p7;
    guid.Data4[5] = p8;
    guid.Data4[6] = p9;
    guid.Data4[7] = p10;
like image 113
Ivan G. Avatar answered Sep 30 '22 10:09

Ivan G.


Where does "Error: Command failed" come from? It's not a standard error message...

You can use the UuidFromString function to do it in native C++.

like image 38
Dean Harding Avatar answered Sep 30 '22 09:09

Dean Harding