2010-10-13 52 views
0

我嘗試將_tcstoul用於字符串到無符號長轉換。使用_tcstoul在無符號長轉換期間檢測無效字符串 - 無法將-ve字符串作爲無效值

但是,它不會將-ve字符串輸入視爲無效輸入。有沒有解決方法?或者我錯過了什麼?

#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返回非負值。

回答

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字符串」是什麼意思?

[編輯] 哦,也許你認爲你應該得到一個下溢錯誤。不,MS docs說「strtoul允許加號(+)或減號( - )符號前綴;前導減號表示返回值被否定。」所以你得到負值包裹到無符號範圍。

乾杯&心連心,

- 阿爾夫

+1

-ve表示否定。 – YeenFei 2010-10-13 02:59:22

+0

好了,問題就解決了:你只是誤解了函數的合同。如果您不想接受負值規範,那麼只需檢查字符串中是否存在前導減號。 – 2010-10-13 03:07:16

+2

當你(無論何人)回答一個答案時,添加一個註釋說明原因。據我所知,我的答案是正確的。如果不是那麼我想知道,其他讀者會從更正中受益。 – 2010-10-14 00:56:57