在无符号长转换期间使用_tcstoul检测无效字符串 - 无法将-ve字符串视为无效值

时间:2010-10-13 02:23:27

标签: c++

我尝试将字符串_tcstoul用于无符号长转换。

但是,它不会将字符串输入视为无效输入。这有什么解决方法吗?或者我错过了什么?

#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();
}

我希望在转换“-22”期间,不应该出现错误,因为“-22”是负值,我期待从_tcstoul返回非负值。

1 个答案:

答案 0 :(得分:0)

将缺少的#include <stdlib.h>添加(并将<cstdio>更改为<stdio.h>)您的代码似乎有效:

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> _

目前还不清楚(至少可以说)你的意思是“-ve string”?

[编辑] 哦,也许你认为你应该得到一个下溢错误。不,MS docs说“strtoul允许加号(+)或减号( - )符号前缀;前导减号表示返回值被否定。”因此,您将负值包含在无符号范围内。

干杯&amp;第h。,

- Alf