C

C++ string转CString

Lan
Lan
2024-06-24 / 2 评论 / 45 阅读 / 正在检测是否收录...

在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;
}
0

评论 (2)

取消
  1. 头像
    wu先生
    Windows 10 · Google Chrome

    技术文,不明觉历呀。

    回复
    1. 头像
      Lan 作者
      Windows 10 · Google Chrome
      @ wu先生

      哈哈哈,最近开始转C++,只做笔记使用,算不上技术文

      回复