關於string::copy()的比較詳細的示例


 std::basic_string::copy

size_type copy( CharT* dest,  size_type count,  size_type pos = 0);

Copies a substring  [pos, pos+count) to character string pointed to by  dest. If the requested substring lasts past the end of the string, or if  count == npos, the copied substring is  [pos, size()). The resulting character string is not null-terminated.

If pos >= size()std::out_of_range is thrown.

Parameters

dest    pointer to the destination character string

pos     position of the first character to include

count  length of the substring

Return value

number of characters copied

 example

 1  #include <string>
 2  #include <iostream>
 3  
 4  using namespace std;
 5  
 6  int main ()
 7  {
 8      size_t length;
 9      char buffer[8];
10      string str("Test string......");
11        
12      length=str.copy(buffer,7,6);       //從buffer6,往后數7個,相當於[ buffer[6], buffer[6+7] )
13      buffer[length]='\0';                        //加上'\0'使得buffer就到buffer[length]為止;
14  
15      cout <<"buffer contains: " << buffer <<endl;
16  
17      length=str.copy(buffer,str.size(),6);        //從buffer6,往后數7個,
18                               //相當於[ buffer[6], buffer[6+7] )
19      buffer[length]='\0';                        //使得buffer就到buffer[length]為止;
20      cout <<"buffer contains: " << buffer <<endl;
21  
22      length=str.copy(buffer,7,0);                //相當於[  buffer[0], buffer[7] )
23      buffer[length]='\0';
24  
25      cout << "buffer contains: " << buffer <<endl;
26  
27      length=str.copy(buffer,7);                   //缺省參數pos,默認pos=0;
28                               //相當於[ buffer[0], buffer[7] )
29      buffer[length]='\0';
30      cout << "buffer contains: " << buffer <<endl;
31      length=str.copy(buffer,string::npos,6);      //相當於[ buffer[7], buffer[npos] )  
32                             //buffer越界賦值,沒有出錯
33      buffer[length]='\0';
34      cout<<string::npos<<endl;                    //string::npos是4294967295
35      cout<<buffer[string::npos]<<endl;            //實際是越界訪問,但沒有出錯,輸出空
36      cout<<buffer[length-1]<<endl;                //實際是越界訪問,但沒有出錯,輸出了其他字符
37      cout << "buffer contains: " << buffer <<endl;
38      length=str.copy(buffer,string::npos);        //相當於[ buffer[0], buffer[npos] )
39                             //buffer越界賦值,沒有出錯
40      buffer[length]='\0';
41      cout << "buffer contains: " << buffer <<endl;        //buffer越界
42      cout<<buffer[string::npos]<<endl;                    //越界訪問,輸出空
43      cout<<buffer[length-1]<<endl;             //越界訪問,沒有輸出str最后一個字符,輸出了其他字符。
44                                               //到這里提示:buffer corrupt!!
45      return 0;
46  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM