tags:

views:

32

answers:

1

I try to use _tcstoul for string to unsigned long conversion.

However, it doesn't treat -ve string input as invalid input. Is there any workaround for this? Or I had missed out something?

#include <cstdio>
#include <tchar.h>

int main() {
    {
        unsigned long iResult(0);
        TCHAR *pszStopString;
        iResult = _tcstoul(_T("2abc"), &pszStopString, 10);
        if( _tcsicmp(pszStopString, _T("")) != 0 ) {
            // OK. We reach here.
            printf("2abc : Error occur during conversion!\n");
        }
    }

    {
        unsigned long iResult(0);
        TCHAR *pszStopString;
        // iResult = 4294967274
        iResult = _tcstoul(_T("-22"), &pszStopString, 10);
        if( _tcsicmp(pszStopString, _T("")) != 0 ) {
            // Nope. We didn't reach here!
            printf("-22 : Error occur during conversion!\n");
        }
    }

    getchar();
}

I expect during conversion of "-22", error shouldn't occur, as "-22" is a negative value, and I am expecting non-negative value returned from _tcstoul.

+1  A: 

Adding the missing #include <stdlib.h> (and also changing <cstdio> to <stdio.h>) your code seems to work:

C:\test> (cl /nologo- 2>&1) | find "++"
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86

C:\test> cl x.cpp & x
x.cpp
2abc : Error occur during conversion!
fine

C:\test> _

It's unclear (to say the least) what you mean by "-ve string"?

[EDIT] Oh, perhaps you think you should get an underflow error. No, the MS docs say "strtoul allows a plus (+) or minus (–) sign prefix; a leading minus sign indicates that the return value is negated.". So you get negative value wrapped into the unsigned range.

Cheers & hth.,

– Alf

Alf P. Steinbach
-ve stands for negative.
YeenFei
OK, problem solved then: you had simply misunderstood the function's contract. If you don't want to accept negative value specifications, then simply check for presence of leading minus in the string.
Alf P. Steinbach
When you (whomever) vote down an answer, add a comment indicating why. As far as I know my answer is correct. If it isn't then I'd like to know, and other readers would benefit from the correction.
Alf P. Steinbach