Other Modifying Methods: copy() and swap()

The copy() method copies a string object, or part thereof, to a designated character array:

size_type copy(charT* s, size_type n, size_type pos = 0) const;

In this case, s points to the destination array, n indicates the number of characters to copy, and pos indicates the position in the string object from which copying begins. Copying proceeds for n characters or until the last character in the string object, whichever comes first. The function returns the number of characters copied. The method does not append a null character, and it is up to the programmer to see that the array is large enough to hold the copy.


Caution

The copy() method does not append a null character, nor does it check whether the destination array is large enough.


The swap() method swaps the contents of two string objects by using a constant time algorithm:

void swap(basic_string& str);

Output and Input

The string class overloads the << operator to display string objects. It returns a reference to the istream object so that output can be concatenated:

string claim("The string class has many features.");
cout << claim << endl;

The string class overloads the >> operator so that you can read input into a string:

string who;
cin >> who;

Input terminates on the end-of-file, on reading the maximum number of characters allowed in a string, or on reaching a white-space character. (The definition of white space depends on the character set and on the type that charT represents.)

There are two getline() functions. The first has this prototype:

template<class charT, class traits, class Allocator>
  basic_istream<charT,traits>& getline(basic_istream<charT,traits>& is,
              basic_string<charT,traits,Allocator>& str, charT delim);

It reads characters from the input stream is into the string str until it encounters the delim delimiter character, reaches the maximum size of the string, or encounters the end-of-file. The delim character is read (that is, removed from the input stream) but not stored. The second version lacks the third argument and uses the newline character (or its generalization) instead of delim:

string str1, str2;
getline(cin, str1);       // read to end-of-line
getline(cin, str2, '.'),  // read to period

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.204