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返回非負值。
-ve表示否定。 – YeenFei 2010-10-13 02:59:22
好了,問題就解決了:你只是誤解了函數的合同。如果您不想接受負值規範,那麼只需檢查字符串中是否存在前導減號。 – 2010-10-13 03:07:16
當你(無論何人)回答一個答案時,添加一個註釋說明原因。據我所知,我的答案是正確的。如果不是那麼我想知道,其他讀者會從更正中受益。 – 2010-10-14 00:56:57