【发布时间】:2010-11-02 19:51:09
【问题描述】:
如何在 MFC 中将CString 对象转换为整数。
【问题讨论】:
标签: visual-c++ mfc
如何在 MFC 中将CString 对象转换为整数。
【问题讨论】:
标签: visual-c++ mfc
我写了一个从字符串中提取数字的函数:
int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
// get startIndex
int startIndex = src.Find(str) + CString(str).GetLength();
// cut the string
CString toreturn = src.Mid(startIndex, length);
// convert to number
return _wtoi(toreturn); // atoi(toreturn)
}
用法:
CString str = _T("digit:1, number:102");
int digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);
【讨论】:
CString s="143";
int x=atoi(s);
或
CString s=_T("143");
int x=_toti(s);
如果您想将CString 转换为int,atoi 将起作用。
【讨论】:
规范的解决方案是使用 C++ 标准库进行转换。根据所需的返回类型,可以使用以下转换函数:std::stoi, std::stol, or std::stoll(或它们的无符号对应物std::stoul, std::stoull)。
实现相当简单:
int ToInt( const CString& str ) {
return std::stoi( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
long ToLong( const CString& str ) {
return std::stol( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
long long ToLongLong( const CString& str ) {
return std::stoll( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
unsigned long ToULong( const CString& str ) {
return std::stoul( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
unsigned long long ToULongLong( const CString& str ) {
return std::stoull( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
所有这些实现都通过异常报告错误(std::invalid_argument 如果无法执行转换,std::out_of_range 如果转换后的值会超出结果类型的范围)。构造临时的std::[w]string也可以抛出。
这些实现可用于 Unicode 和 MBCS 项目。
【讨论】:
如果您正在使用TCHAR.H 例程(隐式或显式),请确保您使用_ttoi() 函数,以便它可以针对Unicode 和ANSI 编译进行编译。
【讨论】:
最简单的方法是使用stdlib.h 中的atoi() 函数:
CString s = "123";
int x = atoi( s );
但是,这并不能很好地处理字符串不包含有效整数的情况,在这种情况下您应该调查strtol() 函数:
CString s = "12zzz"; // bad integer
char * p;
int x = strtol ( s, & p, 10 );
if ( * p != 0 ) {
// s does not contain an integer
}
【讨论】:
在 msdn 中定义:https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
int atoi(
const char *str
);
int _wtoi(
const wchar_t *str
);
int _atoi_l(
const char *str,
_locale_t locale
);
int _wtoi_l(
const wchar_t *str,
_locale_t locale
);
CString 是 wchar_t 字符串。所以,如果你想将 Cstring 转换为 int,你可以使用:
CString s;
int test = _wtoi(s)
【讨论】:
CString 取决于 _UNICODE 和 _MBCS 预处理器符号。它可能存储 UTF-16 编码的 Unicode 字符串、DBCS 字符串或 ASCII 字符串。建议它始终是 Unicode 字符串是错误的,抱歉。
_ttoi 函数可以将CString 转换为整数,宽字符和ANSI 字符都可以工作。详情如下:
CString str = _T("123");
int i = _ttoi(str);
【讨论】:
接受答案的问题在于它不能表示失败。 strtol (STRing TO Long) 可以。它属于一个更大的家族:wcstol(Wide String TO Long,例如 Unicode)、strtoull(TO Unsigned Long Long、64 位+)、wcstoull、strtof(TO Float)和wcstof。
【讨论】:
您可以使用 C atoi 函数(在 try / catch 子句中,因为转换并不总是可能的) 但是 MFC 类中没有什么可以做得更好。
【讨论】:
您也可以使用旧的 sscanf。
CString s;
int i;
int j = _stscanf(s, _T("%d"), &i);
if (j != 1)
{
// tranfer didn't work
}
【讨论】:
CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise
【讨论】: