how can I convert a wchar_t ('9') to a digit in the form of an int (9)?
I have the following code where I check whether or not peek is a digit:
if (iswdigit(peek)) {
// store peek as numeric
}
Can I just subtract '0' or is there some Unicode specifics I should worry about?
If the question concerns just
'9'(or one of the Romandigits), just subtracting
'0'is the correct solution. Ifyou’re concerned with anything for which
iswdigitreturnsnon-zero, however, the issue may be far more complex. The
standard says that
iswdigitreturns a non-zero value if itsargument is “a decimal digit wide-character code [in the current
local]”. Which is vague, and leaves it up to the locale to
define exactly what is meant. In the “C” locale or the “Posix”
locale, the “Posix” standard, at least, guarantees that only the
Roman digits zero through nine are considered decimal digits (if
I understand it correctly), so if you’re in the “C” or “Posix”
locale, just subtracting ‘0’ should work.
Presumably, in a Unicode locale, this would be any character
which has the general category
Nd. There are a number ofthese. The safest solution would be simply to create something
like (variables here with static lifetime):
If you go this way:
UnicodeData.txtfile from the Unicode consortium(“Uncode Character
Database“—this page has a links to both the Unicode data
file and an explination of the encodings used in it), and
information automatically (e.g. when there is a new version of
Unicode)—the file is designed for simple programmatic
parsing.
Finally, note that solutions based on
ostringstreamandistringstream(this includesboost::lexical_cast) will notwork, since the conversions used in streams are defined to only
use the Roman digits. (On the other hand, it might be
reasonable to restrict your code to just the Roman digits. In
which case, the test becomes
if ( wch >= L'0' && wch <= L'9' ),and the conversion is done by simply subtracting
L'0'—always supposing the the native encoding of wide character
constants in your compiler is Unicode (the case, I’m pretty
sure, of both VC++ and g++). Or just ensure that the locale is
“C” (or “Posix”, on a Unix machine).
EDIT: I forgot to mention: if you’re doing any serious Unicode programming, you
should look into ICU. Handling Unicode
correctly is extremely non-trivial, and they’ve a lot of functionality already
implemented.