1

I have an TCHAR array in as follows,

TCHAR input[MAX_PATH] = L"12345";

I want to check whether input TCHAR array is valid signed integer or not? These are the some examples for it and output should be as follows,

  • L"123-" -> false
  • L"123" -> true
  • L"abc" -> false
  • L"-123" -> true
  • 1
    Locale is a mine-field, there are accountants and people in the middle east that think "123-" is a perfectably reasonable number. Simply [convert the string](https://en.cppreference.com/w/c/string/byte/strtol). If you absolutely must use tchar (don't) then use `_tcstol`. – Hans Passant Oct 30 '18 at 11:07

1 Answers1

0

One obvious possibility would be to use a regular expression, with a pattern something like -?[0-9]+.

This guarantees that input contains only an optional sign followed by some number of digits--but does not guarantee that the number of digits will fit in any particular size of integer. If you have more than 20 digits (or so) chances are pretty good that your compiler won't provide an integer type capable of holding it (even though the contents of the string is still a valid integer from a mathematical viewpoint).

Of course, you can also use a bit more manual approach:

bool is_int(char const *input) { 
    auto first = input;

    // check for leading minus sign
    if (*first == '-')
       ++first;

    // then check for digits:
    for ( ; *first && isdigit(*first); ++first)
        ;
    return *first == '\0';
}

If you want to assure that the content of input can actually be converted to an int (as it's defined by the target platform), you can use something like std::stoi.

As an aside: I'd advise dropping the TCHAR stuff. Microsoft designed it as a way of writing code that would work with wide characters on their NT-based platforms (Windows NT/2k/XP) and narrow characters on their Windows 95-based platforms (95/98/SE/Me). The latter are long-since obsolete, removing the primary reason for using this in the first place.

If you really insist on using it anyway, you'll have to do a bit of work to make up for the shortcomings of Microsoft's code. In particular, while they provided mappings in tchar.h for a fair number of string manipulation routines, they never provided (or at least documented) equivalents for things like isdigit, so you'll have to implement your own:

#ifdef _UNICODE
#define istdigit(c) iswdigit(c)
#else
#define istdigit(c) isdigit(c)
#endif

Then the previous code would use the istdigit macro instead of using isdigit.

But as noted, the best approach is to just get rid of the TCHAR nonsense entirely. What little motivation there ever was to use it is long gone.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111