0
if( !( *it >= 0x41 || *it <= 0x5A ) && !( *it >= 0x61 || *it <= 0x7A ) )

I tried something like this but it doesn't catch anything.

  • 6
    Try [isalpha()](http://www.cplusplus.com/reference/cctype/isalpha/) (`!isalpha()` in your case) – Anton Savin Sep 21 '14 at 23:41
  • Are you sure `0x41` to `0x5A` *is* equal to a letter? (There are other ways to *be* sure.) – Jongware Sep 21 '14 at 23:45
  • If you're interested in characters with a particular character value, (i.e. a particular letter of the alphabet), then use character literals (i.e. `'a'`, `'b'`, `'c'`, etc...) , not numeric codes, unless you are trying to obfuscate your code. – Benjamin Lindley Sep 21 '14 at 23:46

2 Answers2

2

There is the standard library function std::isalpha for this:

if( !std::isalpha(static_cast<unsigned_char>(*it))

It tests if a character is a letter or not. Note that the cast before calling std::isalpha is indeed needed.

Community
  • 1
  • 1
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • An alternative is `std::isalpha(*it, std::locale());` which checks a `char` in the default locale. – M.M Sep 22 '14 at 01:14
2

Consider the expression

*it >= 0x41 || *it <= 0x5A

This expression is true for any value at all. Consider a simpler version:

x > 5 || x < 10

Every value x is either greater than 5 or less than 10 (or both). There's no value for which neither of those tests are true.

You probably want

*it >= 0x41 && *it <= 0x5A

which checks whether your character is both greater than 'A' and less than 'Z'. You'll have to make similar changes to the other parts of your test, too.

Of course, a better way is to use the standard isalpha() function, but changing to use that won't help you learn anything about why your given code doesn't work.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285