如何在if语句中比较std::string与TCHAR*类型?
解决std::string与TCHAR*的比较问题
问题出在TCHAR的特性上:它是Windows平台的宏,项目定义_UNICODE时会被解析为wchar_t(宽字符),未定义时则是char(多字节字符)。你的std::string基于char,当处于Unicode模式时,username是wchar_t*类型,两者类型不匹配,自然无法直接比较。
下面是两种可行的解决方法:
方法一:将TCHAR数组转换为std::string
把获取到的TCHAR类型用户名转换成std::string,统一类型后再比较:
std::string user_name = "raso"; TCHAR username[UNLEN + 1]; DWORD username_len = UNLEN + 1; GetUserName(username, &username_len); // 无需强制类型转换,username本身就是TCHAR* std::string username_str; #ifdef _UNICODE // 宽字符转多字节字符串 int buf_size = WideCharToMultiByte(CP_ACP, 0, username, -1, nullptr, 0, nullptr, nullptr); username_str.resize(buf_size); WideCharToMultiByte(CP_ACP, 0, username, -1, &username_str[0], buf_size, nullptr, nullptr); #else // ANSI模式下直接赋值 username_str = username; #endif if (user_name == username_str) { std::cout << "You found the user name!"; }
如果需要UTF-8编码的字符串,可以将CP_ACP替换为CP_UTF8。
方法二:使用TCHAR对应的字符串类型
改用std::basic_string<TCHAR>匹配TCHAR的类型,避免转换开销:
// 用_T宏适配字符串字面量的类型 std::basic_string<TCHAR> user_name = _T("raso"); TCHAR username[UNLEN + 1]; DWORD username_len = UNLEN + 1; GetUserName(username, &username_len); if (user_name == username) { // 输出也要匹配字符类型 #ifdef _UNICODE std::wcout << _T("You found the user name!"); #else std::cout << "You found the user name!"; #endif }
内容的提问来源于stack exchange,提问作者CodexSC
相关产品推荐
相关产品推荐

