《C++笔记》 Part14 MFC的String to CString 转换在多语言系统下乱码问题

2023-12-20 07:58

本文主要是介绍《C++笔记》 Part14 MFC的String to CString 转换在多语言系统下乱码问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • @[TOC](文章目录)
    • Summary
    • C++ convert from string to LPCWSTR
    • C++ convert from LPCWSTR to string
    • 解决方法二
    • 解决方法三
    • Reference

Summary

Encountered problem in convert from string to CString (LPCWSTR), and the reverse convert, find out the way to convert between these two types and tested in Visual Studio with successful result. The unicode setting is configured in the Visual Studio project property page –> Configuration Properties –> General –> Character Set –> Use Unicode Character Set, as below picture shows,
字符集设置为Unicod


Different string types description as below, as How to convert std::string to LPCSTR? mentioned,

  • LPSTR - (long) pointer to string - char *
  • LPCSTR - (long)pointer to constant string - const char *
  • LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *
  • LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t*
  • LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
  • LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *

C++ convert from string to LPCWSTR

As you know, std::string is char* type, while LPCWSTR ,LPWSTR or CString is wchar_t* as long as the Visual Studio configured as Unicode Character Set.

I am using How to convert std::string to LPCSTR? solution as below code solved this problem,

LPWSTR ConvertString(const std::string& instr)
{// Assumes std::string is encoded in the current Windows ANSI codepageint bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);if (bufferlen == 0){// Something went wrong. Perhaps, check GetLastError() and log.return 0;}// Allocate new LPWSTR - must deallocate it laterLPWSTR widestr = new WCHAR[bufferlen + 1];::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);// Ensure wide string is null terminatedwidestr[bufferlen] = 0;// Do something with widestrreturn widestr;//delete[] widestr;
}---------------------

Refer to the How to convert string to LPCTSTR? solution 5, it is the similar solution as above by using MultiByteToWideChar function,

//该转换方式可解决英文及其它语言系统中文字符乱码问题—解决方法一
USES_CONVERSION;
std::wstring s2ws(const std::string& s)
{int len;int slength = (int)s.length() + 1;len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);wchar_t* buf = new wchar_t[len];MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);std::wstring r(buf);delete[] buf;return r;
}std::string s;#ifdef UNICODE
std::wstring stemp = s2ws(s); // Temporary buffer is required
LPCWSTR result = stemp.c_str();
#else
LPCWSTR result = s.c_str();
#endif>---------------------

C++ convert from LPCWSTR to string

To convert from LPCWSTR to string, can split into two steps, first step convert from CString to wchar_t, 2nd step, convert from wchar_t to char*, as below code shows,

 //convert from CString to char* , first from CString to wchar_t then to char *wchar_t wCharString = sFile.GetBuffer(sFile.GetLength()+1); //CString to wchar_tsize_t origsize = wcslen(wCharString) + 1;size_t convertedChars = 0;char gszFile[100] = {0};wcstombs_s(&convertedChars, gszFile, origsize, wCharString , _TRUNCATE); //from wchar_t to char*

Below code from MSDN is working perfectly for the conversion from wchar_t* to char* by using wcstombs_s function,


// crt_wcstombs_s.c
// This example converts a wide character
// string to a multibyte character string.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>#define BUFFER_SIZE 100int main( void )
{size_t   i;char      *pMBBuffer = (char *)malloc( BUFFER_SIZE );wchar_t*pWCBuffer = L"Hello, world.";printf( "Convert wide-character string:\n" );// Conversionwcstombs_s(&i, pMBBuffer, (size_t)BUFFER_SIZE, pWCBuffer, (size_t)BUFFER_SIZE );// Outputprintf("   Characters converted: %u\n", i);printf("    Multibyte character: %s\n\n",pMBBuffer );// Free multibyte character bufferif (pMBBuffer){free(pMBBuffer);}
}

解决方法二

CString string2CString(string str)
{USES_CONVERSION;return A2T((LPSTR)(str.c_str()));
}

解决方法三

CString string2CString(string str)
{USES_CONVERSION;CString cstr;cstr.Format(_T("%s"),str.c_str());return cstr;
}

Reference

  1. MSDN, Converts a sequence of wide characters to a corresponding sequence of multibyte characters
  2. How to convert string to LPCTSTR?
  3. How to convert std::string to LPCSTR?

这篇关于《C++笔记》 Part14 MFC的String to CString 转换在多语言系统下乱码问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/515283

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

JWT + 拦截器实现无状态登录系统

《JWT+拦截器实现无状态登录系统》JWT(JSONWebToken)提供了一种无状态的解决方案:用户登录后,服务器返回一个Token,后续请求携带该Token即可完成身份验证,无需服务器存储会话... 目录✅ 引言 一、JWT 是什么? 二、技术选型 三、项目结构 四、核心代码实现4.1 添加依赖(pom

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja