tcb
tcb

Reputation: 4604

Generating a new guid string in c++ missing some zeros

I tried using the following code to generate a new guid string of 36 characters, but this sometimes prints only 35 or 34 characters. I suppose this is due to the 'zeros' in the guid, but I am unable to clearly see why. Is there a way I can correct this issue?

#include <string>
#include <sstream>
#include <iostream>
#include <windows.h>
#include <iomanip>

int main()
{
    GUID guid;
    CoCreateGuid(&guid);
    std::ostringstream os;
    os.width(8);
    os << std::hex << std::setfill('0') << guid.Data1 << '-';
    os.width(4);
    os << std::hex << std::setfill('0') << guid.Data2 << '-';
    os.width(4);
    os << std::hex << std::setfill('0') << guid.Data3 << '-';
    os.width(2);
    os << std::hex << std::setfill('0')
        << static_cast<short>(guid.Data4[0])
        << static_cast<short>(guid.Data4[1])
        << '-'
        << static_cast<short>(guid.Data4[2])
        << static_cast<short>(guid.Data4[3])
        << static_cast<short>(guid.Data4[4])
        << static_cast<short>(guid.Data4[5])
        << static_cast<short>(guid.Data4[6])
        << static_cast<short>(guid.Data4[7]);

    std::string s(os.str());
    std::cout << s << std::endl;
    std::cout << s.length() << std::endl;
}

Sample output:

f6979589-b13c-416d-bf49-1497d99cd88
35
Press any key to continue . . .

Upvotes: 0

Views: 407

Answers (1)

Arsenii Fomin
Arsenii Fomin

Reputation: 3336

You need to directly set field size for any new value you output, like this:

int main()
{
    GUID guid;
    CoCreateGuid(&guid);
    std::ostringstream os;
    os.width(8);
    os << std::hex << std::setfill('0') << guid.Data1 << '-';
    os.width(4);
    os << std::hex << std::setfill('0') << guid.Data2 << '-';
    os.width(4);
    os << std::hex << std::setfill('0') << guid.Data3 << '-';
    os.width(2);
    os << std::hex << std::setfill('0') << std::setw(2)
        << static_cast<short>(guid.Data4[0]) << std::setw(2)
        << static_cast<short>(guid.Data4[1])
        << '-' << std::setw(2)
        << static_cast<short>(guid.Data4[2]) << std::setw(2)
        << static_cast<short>(guid.Data4[3]) << std::setw(2)
        << static_cast<short>(guid.Data4[4]) << std::setw(2)
        << static_cast<short>(guid.Data4[5]) << std::setw(2)
        << static_cast<short>(guid.Data4[6]) << std::setw(2)
        << static_cast<short>(guid.Data4[7]);

    std::string s(os.str());
    std::cout << s << std::endl;
    std::cout << s.length() << std::endl;
}

Upvotes: 1

Related Questions