Dominique
Dominique

Reputation: 17555

MFC newbie: how to determine if a character is hexadecimal using "FindOneOf()"

I'm new at MFC and I need to do something which sounds extremely simple: determining if a string only contains hexadecimal characters.

For that, I browse through the string (it's a CString) and I verify all characters using the FindOneOf() method, as follows:

int iTest = CString(pszText[i]).FindOneOf((LPCWSTR)"0123456789ABCDEFabcdef");

For some bizarre reason, I always get -1 as a result.

What am I doing wrong?

P.s.1 I prefer not to use the SpanIncluding() method, I find the FindOneOf() quite readable but I don't know how to use it.
P.s.2 Also simple STL seems not to be working: I tried to work with std::isxdigit(pszText[i]) but in order to get this to work, I need to include <locale> and then this function is asking for a second parameter, next to the character I want to check, and a null-pointer is not allowed there (std::isxdigit(pszText[i], nullptr) does not work).

Upvotes: 0

Views: 465

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50883

There are several problems in your code:

This is wrong:

int iTest = CString(pszText[i]).FindOneOf(LPCWSTR)"0123456789ABCDEFabcdef"); 

It should be:

int iTest = CString(pszText[i]).FindOneOf(L"0123456789ABCDEFabcdef");

The cast will simply make the compiler believe that "0123..." is a wide string but it isn't. You need to use the L prefix to indicate that the string is a wide string.

But even then your algorithm won't work because FindOneOf will simply find the first occurrence of any of the characters in the parameter.

Example:

int iTest = CString(L"Z223Zbc").FindOneOf(L"0123456789ABCDEFabcdef");

"Z223Zbc" is obviously not a hexadecimal string, but iTest will contain 1 because the first character of "Z223Zbc" being part of "0123456789ABCDEFabcdef" is '2' and that's at position 1.

iTest will only contain -1 if the string to be tested doesn't contain any hexadecimal characters as for example "xyz".

Therefore this solution is appropriate:

  #include <cwctype>
  ...
  WCHAR string[] = L"123abcX";
  bool ishexstring = true;    // assume the string is a hex string
  for (int i = 0; ; i++)
  {
    WCHAR c = string[i];
    if (c == 0)
      break;                  // end of string => we exit the looop
    if (!std::iswxdigit(c))
    {
      ishexstring = false;    // c is no hex digit
      break;                  // exit loop
    }
  }

This algorithm should be put into a function, but I'm leaving this as an exercise for the reader.

Solution using SpanIncluding (less efficient because we need tot construct a temporary CString):

bool ishexstring = CString(string).SpanIncluding(L"0123456789ABCDEFabcdef") == str;

Upvotes: 2

Related Questions