A comment on an earlier version of this answer of mine alerted me to the fact that I can't assume that 'A'
, 'B'
, 'C'
etc. have successive numeric values. I had sort of assumed the C or C++ language standards guarantee that this is the case.
So, how should I determine whether consecutive letter characters' values are themselves consecutive? Or rather, how can I determine whether the character constants I can express within single quotes have their ASCII codes for a numeric value?
I'm asking how to do this both in C and in C++. Obviously the C way would work in C++ also, but if there's a C++ish facility for doing this I'm interested in that as well. Also, I'm asking about the newest relevant standards (C11, C++17).
You can use the preprocessor to check if a particular character maps to the charset:
#include <iostream>
using namespace std;
int main() {
#if ('A' == 65 && 'Z' - 'A' == 25)
std::cout << "ASCII" << std::endl;
#else
std::cout << "Other charset" << std::endl;
#endif
return 0;
}
The drawback is, you need to know the mapped values in advance.
The numeric chars '0'
- '9'
are guaranteed to appear in consecutive order BTW.