溫馨提示×

c字符串轉(zhuǎn)換為c++ string類的方法

c++
小樊
82
2024-08-28 02:34:57
欄目: 編程語言

在C++中,可以使用std::string構(gòu)造函數(shù)將C字符串(以空字符結(jié)尾的字符數(shù)組)轉(zhuǎn)換為std::string對象

#include<iostream>
#include<string>

int main() {
    // 定義一個C字符串
    const char* c_str = "Hello, World!";

    // 使用C字符串初始化std::string對象
    std::string cpp_str(c_str);

    // 輸出轉(zhuǎn)換后的std::string對象
    std::cout << "C++ string: " << cpp_str<< std::endl;

    return 0;
}

在這個示例中,我們首先定義了一個C字符串c_str。然后,我們使用std::string構(gòu)造函數(shù)將其轉(zhuǎn)換為std::string對象cpp_str。最后,我們輸出轉(zhuǎn)換后的std::string對象。

0