设为首页 加入收藏

TOP

string与二进制数据
2011-01-31 09:26:51 】 浏览:1186
Tags:string 二进制数据
  1. C99 有很多和 string 相关的函数, 如 strcat , strchr , strcmp , strcpy , strlen , strncat , strncmp , strncpy 等。 然而使用 C++(www.cppentry.com) 编程(www.cppentry.com)时,所有和 string 相关的操作均可以使用 string 类的相关接口完成, string 提供和原来 C 接口类似的 功能和性能,同时提供更高的安全性。   
  2.   
  3. String 类 有一个特 性: a string of length n must manage a block of memory whose size is at least n + 1 。 即长度为 n 的 string 对象,其内存空间至少为 n+1 个字符,且最后一个字符为 ’\0’ 。   
  4.   
  5. 不过在进行 string 操作时,有一点必须牢记: C/C++(www.cppentry.com) 语言的 string 是以 ’\0’ 结尾的,对不以 ’\0’ 结尾的 string 进行操作容易引发错误,甚至导致内存溢出等 crash 。   
  6.   
  7. C++(www.cppentry.com) 的 string 类,除了用于处理常规 string 操作 外,其本身也可用于存储各种数据 ,如文件数据,此时并不要求 string 对象必须以 ’\0’ 结尾。使用者采用 string( const char* str, size_type length ); 来封装特定长度的 char* 数据块。 String 类的各种运算符将保证数据传递的完整性,即 string 对象。   
  8.   
  9. 示例:   
  10.   
  11. view sourceprint   
  12. 01 #include <iostream>    
  13.   
  14. 02 using namespace std;    
  15.   
  16. 03      
  17.   
  18. 04 int main() {    
  19.   
  20. 05         std::string str("test string");    
  21.   
  22. 06         cout<<str<<"  "<<str.c_str()<<endl;    
  23.   
  24. 07         cout<<str.size()<<endl;    
  25.   
  26. 08      
  27.   
  28. 09         char* buf = new char[str.size()+1];    
  29.   
  30. 10         memset(buf, 0, sizeof(buf));    
  31.   
  32. 11      
  33.   
  34. 12         string test(buf, str.size());   // 封装非字符数据    
  35.   
  36. 13         cout<<test<<"  "<<test.c_str()<<endl;    
  37.   
  38. 14         cout<<test.size()<<endl;    
  39.   
  40. 15      
  41.   
  42. 16         memcpy(buf, str.c_str(), str.size());    
  43.   
  44. 17      
  45.   
  46. 18         test = string(buf, str.size());   // 封装字符数据,并自动加上 ’\0’ 结束符    
  47.   
  48. 19         cout<<test<<"  "<<test.c_str()<<endl;    
  49.   
  50. 20         cout<<test.size()<<endl;    
  51.   
  52. 21      
  53.   
  54. 22         return 0;    
  55.   
  56. 23 }   
  57. 其输出:  
  58.   
  59. test string  test string   
  60.   
  61. 11   
  62.   
  63.     
  64.   
  65. 11   
  66.   
  67. test string  test string   
  68.   
  69. 11   
  70.   
  71. 说明:这个例子说明:当使用 string( const char* str, size_type length ); 来构造string对象时,string对象的长度由外部指定,数据则来自 str ,如果 length 大于 str 地址范围,可能引发 crash!   
  72.   
  73. 这个例子也说明了 string 可用于封装数据,即使是 ’\0’ 的数据。因此,string类可以用于存储各种数据,字符串、非字符串 (图片,视频)等数据。   
  74.   
  75. 注 意:将数据拷贝到内存时,不要使用strcpy, 应该使用memcpy,因为strcpy、strncpy碰到 ’\0’ 将认为拷贝结束。 总之,不 要使用和str*** 相关的函数去操作内存数据,除非数据只能是string(memcpy完全可拷贝任何数据) 。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇ifstream读取文件至string string.. 下一篇C++中获取高精度时间差

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目