天天看点

c++中c_str()的用法详解

!!!c_str()就是将C++的string转化为C的字符串数组!!!

C中没有string,所以函数c_str()就是将C++的string转化为C的字符串数组,c_str()生成一个const char *指针,指向字符串的首地址。

下文通过3段简单的代码比较分析,具体说明c_str()的使用方法和注意事项。

用法一:

首先看一段代码:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
	const char *c;
	string s = "1234";
	c = s.c_str(); //c最后指向的内容是垃圾,因为当s对象被析构,其内容被处理,
	               //同时,编译器也将报错——将一个const char *赋与一个char *。
	               //因此要么现用现转换,要么把它的数据复制到用户自己可以管理的内存中
	cout<<c<<endl;
	s = "abcd";
	cout<<c<<endl;
	system("pause");
}
           

结果是:

1234

abcd

如果程序中继续使用c指针,导致的错误是不可预估的。比如:1234变成abcd

用法二:

 使用strcpy()函数 等来操作方法c_str()返回的指针 。

更好处理为:

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
	//更好的方法是将string数组中的内容复制出来 所以会用到strcpy()这个函数
	char *c = new char[20];
	string s = "1234";
	// c_str()返回一个客户程序可读不可改的指向字符数组的指针,不需要手动释放或删除这个指针。
	strcpy(c,s.c_str());
	cout<<c<<endl;
	s = "abcd";
	cout<<c<<endl;
	system("pause");
}
           

结果是:

1234

1234

用法三:

再举个例子

c_str()以char*形式传回string内含字符串

如果一个函数要求char*参数,可以使用c_str()方法:

string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!"
system("pause");
           

结果是:

Hello World!

参考资料:

  1. C++ c_str() 用法 ↩︎ ↩︎
  2. c++中c_str()的用法详解 ↩︎

继续阅读