C/C++多场景字符类型转换实战指南

白榆
白榆
发布时间:2026-10-15| 926人浏览过
原创

本文总结C/C++开发中高频出现的字符转换需求,提供std::wstring、winrt::hstring、CString与std::string的互转代码示例。针对C++17后弃用的codecvt情况,推荐使用WideCharToMultiByte实现安培/UTF-8无损转换,同时涵盖基础指针与数值间的字符串互转方法。

在Windows与跨平台C/C++混合开发中,常需处理宽窄字符、MFC对象及UWP API之间的类型桥接。本文汇总了std::wstring与utf8互转的最佳实践(替代已弃用的codecvt)、winrt::hstring的现代用法,以及MFC CString和底层const char*的各种转换技巧。

一、std::string 与 std::wstring 互转

早期教程常使用 std::wstring_convert,但由于 C++17 起该功能被弃用,现代 C++ 项目更推荐使用 Windows API 中的 WideCharToMultiByte 和 MultiByteToWideChar 进行底层控制。这种方法能精确指定编码页(如ACP或UTF8)。

第1步:利用 WideCharToMultiByte 实现宽窄字符互转

以下封装好的辅助类函数覆盖了 ANSI 与 UTF-8 两种常用场景。使用时需确保调用方已包含 Windows.h。

std::string MyTools::ConvertWideToANSI(const std::wstring& wstr)
{
    int count = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL);
    std::string str(count, 0);
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &str[0], count, NULL, NULL);
    return str;
}
 
std::wstring MyTools::ConvertAnsiToWide(const std::string& str)
{
    int count = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), NULL, 0);
    std::wstring wstr(count, 0);
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), &wstr[0], count);
    return wstr;
}
 
std::string MyTools::ConvertWideToUtf8(const std::wstring& wstr)
{
    int count = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL);
    std::string str(count, 0);
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &str[0], count, NULL, NULL);
    return str;
}
 
std::wstring MyTools::ConvertUtf8ToWide(const std::string& str)
{
    int count = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), 0, NULL);
    std::wstring wstr(count, 0);
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), &wstr[0], count);
    return wstr;
}

二、winrt::hstring 与 std::string 互转

在使用 C++/WinRT 编写 UWP 或 WinUI 应用时,经常需要在标准字符串和 winrt::hstring 之间跳转。hstring 是 Windows 运行时字符串的标准类型,具有值语义。

第1步:直接初始化与自动推导

winrt::to_hstring 接受多种类型的参数自动转换;反之通过 winrt::to_string 获取纯文本。

// 直接声明一个winrt::hstring
winrt::hstring w{L"zh-CN"};
// 调用winrt::to_hstring方法直接把std::string转为winrt::hstring
winrt::hstring htr = winrt::to_hstring("this is a std string");
 
// 调用winrt::to_string转为std::string
winrt::hstring text{L"zh-CN测试文本"};
std::string temp = winrt::to_string(text); // 注意:如果内部含宽字符,可能需要额外处理以正确转为UTF8或ANSI

三、const char* 和 char* 互转

这属于底层指针修饰符移除的操作,适用于旧版遗留代码的接口兼容。

第1步:移除 const 限定符(不安全需谨慎)

将常量字符串转为可写指针,若后续修改内存可能导致未定义行为。

const char *filePath= "abc";
char *newPath = const_cast(filePath); // 谨慎使用

第2步:添加 const 限定符

从非定指针赋给定指针,这是默认的安全操作。

const char* cpc;
char* pc = "abcde";
cpc = pc;

四、Qt 环境下的 QString 与 std::string 互转

在 Qt 框架开发中,由于 QString 基于 Unicode 且为隐式共享类,转换过程涉及临时拷贝。

第1步:双向转换函数调用

std::string qtStr = "asdfg";
QString path = QString::fromStdString(qtStr); // 假定系统locale匹配,否则需用fromUtf8
std::string backToString = path.toStdString();

五、补充:MFC (CString) 及相关转换

第1步:CString 与 char* 互转

MFC 环境下最标准的做法是使用 GetBuffer() 获取内部缓冲区,操作完毕后必须调用 ReleaseBuffer() 更新状态。

CString string1 = _T("string");
char *str = string1.GetBuffer();
// ... 使用 str ...
string1.ReleaseBuffer(); // 务必释放

或者直接使用强转宏:
char *str = (LPTSTR)(LPCTSTR)string1;

第2步:基础字符与整型转换

在需要简单格式化数字到字符串时,可使用标准库函数:

  • 字符串转整数:使用 atoi(val)。
  • 整数转字符串:使用 sprintf(buf, "%d", num) 比 VC 专有的 itoa 更具便携性。
以上就是C/C++在Windows及跨平台环境中各类常见字符类型转换的详细内容,更多关于C++字符串处理机制的资料请关注本站其它相关文章!
相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Python

Python

3.15.0 · Windows

Python 官方解释器与标准库,适合 Python 学习和应用开发。

Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。