• C风格字符串和C++string对象的相互转化


    一、C风格的字符串转化为C++的string对象

    C++中,string 类能够自动将C 风格的字符串转换成string 对象
     
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
    
        char str[] = "hello, world!"; //char str[] = "hello, world!";
        string str2(str); //string str2 = str;
        cout << "C风格:" << str << endl;
        cout << "C++风格:" << str2 << endl;
        return 0;
    
    }

    二、C++的string对象转化为C风格的字符串

    string提供一个方法可以直接返回字符串的首指针地址,即string.c_str()。比如string str = "Hi !"转换为char*类型。

    const char* mystr = str.c_str(),在这里注意要加上const,因为c_str()返回的是const char *类型

     
  • 相关阅读:
    23.课程应用接口
    22.课程页面设计
    21.手机接口
    20.云通讯
    19.JWT
    18.权限认证
    解决github下载慢的终极方法
    vs code 配置c/c++环境
    Python 字符编码处理总结
    Python编码
  • 原文地址:https://www.cnblogs.com/fuqia/p/9648370.html
Copyright © 2020-2023  润新知