Convert wchar_t to int

Lasse Espeholt picture Lasse Espeholt · May 20, 2011 · Viewed 29k times · Source

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?

Answer

Daren Thomas picture Daren Thomas · May 20, 2011

Look into the atoi class of functions: http://msdn.microsoft.com/en-us/library/hc25t012(v=vs.71).aspx

Especially _wtoi(const wchar_t *string); seems to be what you're looking for. You would have to make sure your wchar_t is properly null terminated, though, so try something like this:

if (iswdigit(peek)) {
    // store peek as numeric
    wchar_t s[2];
    s[0] = peek;
    s[1] = 0;
    int numeric_peek = _wtoi(s);
}