C++ string转CString
2024年06月24日
在C++ 中,将 std::string
转换为 CString
可以使用以下几种方法。其中最简单和高效的一种是使用 CString
的构造函数进行直接转换。以下是几种常见的方法:
方法一:使用 CString 的构造函数
#include <atlstr.h> // CString 需要这个头文件
#include <string>
int main() {
std::string stdStr = "Hello, World!";
CString cstr(stdStr.c_str());
// 这里可以对 cstr 进行进一步操作
return 0;
}
方法二:使用 CString 的赋值运算符
#include <atlstr.h>
#include <string>
int main() {
std::string stdStr = "Hello, World!";
CString cstr;
cstr = stdStr.c_str();
// 这里可以对 cstr 进行进一步操作
return 0;
}
方法三:使用 CString 的 Format
方法
#include <atlstr.h>
#include <string>
int main() {
std::string stdStr = "Hello, World!";
CString cstr;
cstr.Format(_T("%s"), stdStr.c_str());
// 这里可以对 cstr 进行进一步操作
return 0;
}
总结
最简洁和高效的方式是直接使用 CString
的构造函数,这是因为它能够直接从 std::string
的 C 字符串 (c_str()
) 创建 CString
对象。这样避免了额外的步骤和临时对象的创建。
#include <atlstr.h>
#include <string>
int main() {
std::string stdStr = "Hello, World!";
CString cstr(stdStr.c_str());
// 这里可以对 cstr 进行进一步操作
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步