在 C++ 中,可以使用 std::string 类来表示字符串。如果有一个 char 数组,可以使用以下方法将其转换为 std::string:

std::string strTitle(wTitle);

该代码将 wTitle 数组的内容复制到 strTitle 字符串中。需要注意的是,这种方法只适用于数组大小不超过 std::string 最大容量的情况。

如果您需要处理更大的数组,可以使用 std::string 的构造函数,该构造函数接受一个 char 指针和一个长度作为参数:

std::string strTitle(wTitle, sizeof(wTitle));

此代码将 wTitle 数组的所有内容复制到 strTitle 字符串中。

示例代码:

#include <iostream>
#include <string>

int main() {
    char wTitle[70] = "Hello, World!";
    std::string strTitle(wTitle);
    std::cout << strTitle << std::endl;
    return 0;
}

输出:

Hello, World!

总结:

可以使用 std::string 的构造函数或赋值运算符将 char 数组转换为 std::string。选择哪种方法取决于您需要处理的数组大小。

C++ 将 char 数组转换为 std::string

原文地址: https://www.cveoy.top/t/topic/oOqt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录