Files
gjm 164968b62e chore
把非utf8-bom编码的cpp/h文件改为 utf8 bom 编码, msvc识别utf8编码时,如果不是bom格式的,会使用当前cp_oem来解码.
2026-10-04 00:04:20 +08:00

101 lines
3.1 KiB
C++

#pragma once
#include <stdlib.h> // _tcstol, _tcstod
#include <errno.h> // ERANGE
#include <float.h> // DBL_MAX, DBL_MIN
#include <atlstr.h> // CString
namespace StrConverter
{
// =========================================================================
// 1. 字符串转整数 (String -> Int)
// 返回值:
// true = 转换完美成功 (整个字符串都是数字,且未越界)
// false = 转换失败 (包含非法字符、空字符串或数值越界)
// =========================================================================
inline bool ToInt(LPCTSTR pszStr, int &outVal)
{
// 1. 基本空指针检查
if (pszStr == NULL || *pszStr == _T('\0'))
return false;
TCHAR* pEnd = NULL;
// 重置错误码,用于检测溢出
errno = 0;
// 2. 执行转换 (强制 10 进制)
// C++98 中 int 和 long 在 Windows 下通常都是 32位,
// 如果你需要 64位支持,需用 _tcstoi64
long lVal = _tcstol(pszStr, &pEnd, 10);
// 3. 严格检查
// 条件 A: *pEnd == '\0' 表示字符串被读完了,没有剩余垃圾字符 (如 "123a")
// 条件 B: errno != ERANGE 表示没有发生溢出 (如输入了 99999999999)
if (*pEnd == _T('\0') && errno != ERANGE)
{
outVal = (int)lVal;
return true;
}
return false;
}
// 重载版本:支持 CString
inline bool ToInt(const CString& str, int &outVal)
{
return ToInt((LPCTSTR)str, outVal);
}
// =========================================================================
// 2. 字符串转浮点数 (String -> Double)
// 返回值:
// true = 转换成功
// false = 转换失败
// =========================================================================
inline bool ToDouble(LPCTSTR pszStr, double &outVal)
{
if (pszStr == NULL || *pszStr == _T('\0'))
return false;
TCHAR* pEnd = NULL;
errno = 0;
// 执行转换
double dVal = _tcstod(pszStr, &pEnd);
// 检查规则同上
if (*pEnd == _T('\0') && errno != ERANGE)
{
outVal = dVal;
return true;
}
return false;
}
// 重载版本:支持 CString
inline bool ToDouble(const CString& str, double &outVal)
{
return ToDouble((LPCTSTR)str, outVal);
}
// =========================================================================
// 3. 容错版本 (可选)
// 如果你不想写 if (ToInt(...)),只想拿到一个值,失败了就给默认值
// =========================================================================
inline int ToIntDef(LPCTSTR pszStr, int nDefault = 0)
{
int val;
if (ToInt(pszStr, val))
return val;
return nDefault;
}
inline double ToDoubleDef(LPCTSTR pszStr, double dDefault = 0.0)
{
double val;
if (ToDouble(pszStr, val))
return val;
return dDefault;
}
}