分享

关于 c_str()

 幸福的落叶@ing 2010-10-06
 c_str() 是c++ 中 string类 (class) 的 函数,它能把 string类 的对象里的字符串 转换成 C 中 char 型变量的字符串。c_str()返回了一个指向常量数组的指针,例如:
      string s1 = "hello";  
      const char* str = s1.c_str();

 

    由于c_str函数的返回值是const char* 的,若想直接赋值给char*,就需要我们进行相应的操作转化,下面是这一转化过程。需要注意的是,操作c_str()函数的返回值时,只能使用c字符串的操作函数,如:strcpy()等函数.因为,string对象可能在使用后被析构函数释放掉,那么你所指向的内容就具有不确定性.


#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main ()
{
  char* cstr,* p;
  string str("Please split this phrase into tokens.");
  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str()); //c_str()返回的是一个临时的指针变量,不能对其操作.
  // cstr now contains a c-string copy of str
  p=strtok (cstr," ");
  while (p!=NULL)
  {
    cout << p << endl;
    p=strtok(NULL," ");
  }
  delete []cstr; 
  return 0;
}

输出:
Please
split
this
phrase
into
tokens.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多