关于c_str( ) 冷夜

原文地址:关于c_str( )作者:Jae_Joong

    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.

原文地址:https://www.cnblogs.com/gamesky/p/2683502.html