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.