swscanf implementation in casting

Viewed 44

I am working on a project in which I need to use swscanf() to find out if a string value is either Decimal or Hex. After that, I am putting that value in a variable. The function is:

Input_String(const std::wstring& a, const StringFormat b)
{
    unsigned int Value;
    switch (b)
    {
    case Decimal:
        swscanf(string.c_str(), L"%u", &Value);
        break;
    case HexCode:
        swscanf(string.c_str(), L"%x", &Value);
        break;
    default:
        swscanf(string.c_str(), L"%u", &Value);
        break;
    }
} 

StringFormat is an enum for format checking.

I want to create an alternative for the swscanf() for the case. Is there any possible way to do this?

1 Answers

Putting the errors in your code (like using string in place of what presumably should be a, and your function not having either a declared type or a return value) aside … if you only have a choice between hex and decimal, you can initialize the format argument to swscanf according to the passed enumeration type:

#include <iostream>
#include <string>

typedef enum {
    Decimal, HexCode
} StringFormat;

unsigned int Input_String(const std::wstring& a, const StringFormat b)
{
    unsigned int Value;
    const wchar_t* fmt = (b == HexCode) ? L"%x" : L"%u";
    if (swscanf(a.c_str(), fmt, &Value) != 1) {
        Value = UINT_MAX; // Always check return value and handle any error!
    }
    return Value;
}

Or, if you prefer, you could put that ternary expression itself as the argument:

unsigned int Input_String(const std::wstring& a, const StringFormat b)
{
    unsigned int Value;
    if (swscanf(a.c_str(), (b == HexCode) ? L"%x" : L"%u", &Value) != 1) {
        Value = UINT_MAX; // Error condition
    }
    return Value;
}

Note that, in both the above code samples, some compilers will complain (issue a warning) about not using a string literal for the format argument to swscanf (MSVC does but clang-cl doesn't). However, this is valid (if unconventional) code.

Related