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;
}
 
 
 
posted @   firespeed  阅读(92)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起