简体   繁体   English

将MFC的CString转换为ASCII和UNICODE的int

[英]convert MFC's CString to int for both ASCII and UNICODE

Converting CString to an int in ASCII mode is as simple as 在ASCII模式下将CString转换为int很简单

CString s("123");
int n = atoi(s);

However that doesn't work for projects in UNICODE mode as CString becomes a wide-char string. 但是,这对于UNICODE模式下的项目不起作用,因为CString变为宽字符字符串。

How do I write my code to cover both ASCII and UNICODE modes without extra if statements? 如何编写我的代码以覆盖ASCII和UNICODE模式,而没有多余的if语句?

There's a special version of CString that uses multibyte characters even if your build is specified for wide characters - CStringA . 有一个特殊版本的CString使用多字节字符,即使您的构建是为宽字符指定的CStringA It will also convert from wide characters automatically. 它还将自动从宽字符转换。

CString s(_T("123"));
CStringA sa = s;
int n = atoi(sa);

There's a corresponding CStringW that only uses wide characters. 有一个相应的CStringW只使用宽字符。

Turns out there's a _ttoi() available just for that purpose: 原来有一个_ttoi()可用_ttoi()目的:

CString s( _T("123") );
int n = _ttoi(s);

This works for both modes with no extra effort. 这对两种模式都适用,而无需额外的努力。

If you need to convert hexadecimal (or other-base) numbers you can resort to a more generic strtol() variant: 如果需要转换十六进制(或其他基数)数字,则可以求助于更通用的strtol()变体:

CString s( _T("0xFA3") );
int n = _tcstol(s, nullptr, 16);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM