偶遇C_STR()

来源:互联网 发布:php 连接sqlserver 编辑:程序博客网 时间:2024/04/28 03:07
c_str函数的使用

c_str函数的返回值是const char*的,不能直接赋值給char*,所以就需要我们进行相应的操作转化,下面就是这一转化过程。

c++语言提供了两种字符串实现,其中较原始的一种只是字符串的c语言实现。与C语言的其他部分一样,它在c+的所有实现中可用,我们将这种实现提供的字符串对象,归为c-串,每个c-串char*类型的。

标准头文件<cstring>包含操作c-串的函数库。这些库函数表达了我们希望使用的几乎每种字符串操作。
当调用库函数,客户程序提供的是string类型参数,而库函数内部实现用的是c-串,因此需要将string对象,转化为char*对象,而c_str()提供了这样一种方法,它返回一个客户程序可读不可改的指向字符数组的指针。
举例:
#include <iostream>
#include <string>
using namespace std;

void main()
{
string add_to = "hello";
const string add_on = "tianqi";
const char *cfirst = add_to.c_str();
const char *csecond = add_on.c_str();
       char *copy = new char[strlen(cfirst)+strlen(csecond)+1];
strcpy(copy, cfirst);
strcat(copy,csecond);
add_to = copy;
cout<<add_to<<endl;

}

例二:

       string str = "zhupo";
const char *ps = str.c_str();
char *cp = new char[strlen(ps)+1];
strcpy(cp, ps);
       cout<<cp<<endl;


原创粉丝点击