// hello worldstring str =" /> // hello worldstring str =" />

std::string 与 char* 之间的转换

std::string 与 char* 之间的转换

std::string 是c++标准库里面其中一个,封装了对字符串的操作
一、把string转换为char*有三种方法
1. .data
2. .c_str
3. .copy

using namesapce std;string str = "hello world";const char *p = str.data();printf(p);//==>//  hello world


string str = "hello world";const char *p = str.c_str();printf(p);//==>//  hello world


string str = "hello world";char p[40];str.copy(p, 5, 0);//这里5,代表复制几个字符,0代表复制的位置  *(p + 5) = '\0';//要手动加上结束符printf(p);//==>//  hello


2:把char*转换为string的方法

const char* p = "Hello world";std::string str = p; // 可以对str直接赋值cout << str;//==>//  hello world


注:
当定义一个string类型的变量后,使用printf_s会出现问题。

std::string str = "Hello world";printf_s("%s", str);//==>//  乱码


这样的输出是有问题的,因为%s要求的是后面对象的首地址。但是string不是这样的类型,所以会出错。使用

cout << str << endl; //这样输出是没有问题的。//==>//  hello world  


或者

printf_s("%s", str.c_str());//==>//  hello world 


原文链接:https://blog.csdn.net/u014801811/article/details/80113382

免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部