现在的位置: 首页 > 综合 > 正文

string char* CString

2013年10月08日 ⁄ 综合 ⁄ 共 1123字 ⁄ 字号 评论关闭

     const char *c_str();
  c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
  这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
  注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
  比如:最好不要这样:
  char* c;
  string s="1234";
  c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理
  应该这样用:
  char c[20];
  string s="1234";
  strcpy(c,s.c_str());
  这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
  再举个例子
  c_str() 以 char* 形式传回 string 内含字符串
  如果一个函数要求char*参数,可以使用c_str()方法:
  string s = "Hello World!";
  printf("%s", s.c_str()); //输出 "Hello World!"

 

    Objects of type string belonging to the C++ template class basic_string<char> are not necessarily null terminated. The null character ' /0 ' is used as a special character in a C-string to mark the end of the string but has no special meaning in an object of type string and may be a part of the string just like any other character. There is an automatic conversion from const char* into strings, but the string class does not provide for automatic conversions from C-style strings to objects of type basic_string<char>.

The returned C-style string should not be modified, as this could invalidate the pointer to the string, or deleted, as the string has a limited lifetime and is owned by the class string.

 

从“CString”转换为“const char *”
添加(char *)(LPCTSTR)。

抱歉!评论已关闭.