The string Class(PART 1)
Constructing a String
Table 16.1 string Class Constructors
Constructor | Description |
(#1) string(const char * s) | Initializes a string object to the NBTS pointed to by s. |
(#2) string(size_type n, char c) | Creates a string object of n elements, each initialized to the character c. |
(#3) string(const string & str) | Initializes a string object to the string object str (copy constructor). |
(#4) string() | Creates a default string object of 0 size (default constructor). |
(#5) string(const char * s, size_type n) |
Initializes a string object to the NBTS pointed to by s and continues for n characters, even if that exceeds the size of the NBTS. |
(#6) template<class Iter> string(Iter begin, Iter end) |
Initializes a string object to the values in the range [begin, end), where begin and end act like pointers and specify locations; the range includes begin and is up to but not including end. |
(#7) string(const string & str, size_type pos, size_type n = npos) |
Initializes a string object to the object str, starting at position pos in str and going to the end of str or using n characters, whichever comes first. |
(#8) string(string && str) noexcept (C++11) |
Initializes a string object to the string object str; str may be altered (move constructor). |
(#9) string(initializer_list<char> il) (C++11) |
Initializes a string object to the characters in the initializer list il. |
1 // str1.cpp -- introducing the string class 2 #include <iostream> 3 #include <string> 4 // using string constructors 5 6 int main() 7 { 8 using namespace std; 9 string one("Lottery Winner!"); // ctor #1 10 cout << one << endl; // overloaded << 11 string two(20, '$'); // ctor #2 12 cout << two << endl; 13 string three(one); // ctor #3 14 cout << three << endl; 15 one += " Oops!"; // overloaded += 16 cout << one << endl; 17 two = "Sorry! That was "; 18 three[0] = 'P'; 19 string four; // ctor #4 20 four = two + three; // overloaded +, = 21 cout << four << endl; 22 char alls[] = "All's well that ends well"; 23 string five(alls,20); // ctor #5 24 cout << five << "!\n"; 25 string six(alls+6, alls + 10); // ctor #6 26 cout << six << ", "; 27 string seven(&five[6], &five[10]); // ctor #6 again 28 cout << seven << "...\n"; 29 string eight(four, 7, 16); // ctor #7 30 cout << eight << " in motion!" << endl; 31 // std::cin.get(); 32 return 0; 33 }
The sixth constructor has a template argument:
template<class Iter> string(Iter begin, Iter end);
The intent(含义) is that begin and end act like pointers pointing to two locations in memory.
(In general, begin and end can be iterators, generalizations of pointers extensively(广泛)
used in the STL.) The constructor then uses the values between the locations pointed to
by begin and end to initialize the string object it constructs.The notation [begin, end),
borrowed from mathematics, means the range includes begin but doesn’t include end.
That is, end points to a location one past the last value to be used. Consider the following
statement:
string six(alls+6, alls + 10); // ctor #6
Because the name of an array is a pointer, both alls + 6 and alls + 10 are type
char *, so the template is used with Iter replaced by type char *.The first argument
points to the first w in the alls array, and the second argument points to the space following
the first well.Thus, six is initialized to the string "well". Figure 16.1 shows how
the constructor works.
Now suppose you want to use this constructor to initialize an object to part of another
string object—say, the object five.The following does not work:
string seven(five + 6, five + 10);
The reason is that the name of an object, unlike the name of an array, is not treated as
the address of an object, hence five is not a pointer and five + 6 is meaningless. However,
five[6] is a char value, so &five[6] is an address and can be used as an argument
to the constructor:
string seven(&five[6], &five[10]);// ctor #6 again
The seventh constructor copies a portion of one string object to the constructed
object:
string eight(four, 7, 16); // ctor #7
This statement copies 16 characters from four to eight, starting at position 7 (the
eighth character) in four.
The string Class Input
Another useful thing to know about a class is what input options are available. For C-style
strings, recall, you have three options:
1 char info[100]; 2 cin >> info; // read a word 3 cin.getline(info, 100); // read a line, discard(丢弃) \n 4 cin.get(info, 100); // read a line, leave \n in queue
For string objects, recall, you have two options:
1 string stuff; 2 cin >> stuff; // read a word 3 getline(cin, stuff); // read a line, discard \n
Both versions of getline() allow for an optional argument(可选参数) that specifies which character
to use to delimit(确定边界) input:
1 cin.getline(info,100,':'); // read up to :, discard : 2 getline(stuff, ':'); // read up to :, discard :
The main operational difference is that the string versions automatically size the target
string object to hold the input characters:
1 char fname[10]; 2 string lname; 3 cin >> fname; // could be a problem if input size > 9 characters 4 cin >> lname; // can read a very, very long word 5 cin.getline(fname, 10); // may truncate(截断) input 6 getline(cin, fname); // no truncation
The automatic sizing feature allows the string version of getline() to dispense with(免除)
the numeric parameter(数值参数) that limits the number of input characters to be read.
A design difference is that the C-style string input facilities are methods of the
istream class, whereas the string versions are standalone(独立的) functions.That’s why cin is an
invoking(调用) object for C-style string input and a function argument for string object input.
The getline() function for the string class reads characters from the input and
stores them in a string object until one of three things occurs:
1. The end-of-file is encountered, in which case eofbit of the input stream is set,
implying that both the fail() and eof() methods will return true.
2. The delimiting character (\n, by default) is reached, in which case it is removed
from the input stream but not stored.
3. The maximum possible number of characters (the lesser(较小的) of string::npos and the
number of bytes in memory available for allocation) is read, in which case failbit
of the input stream is set, implying that the fail() method will return true.
Because the
input functions for string objects work with streams and recognize the end-of-file, you
can also use them for file input. Listing 16.2 shows a short example that reads strings from
the file. It assumes that the file contains strings separated by the colon(冒号) character and uses
the getline() method of specifying a delimiter(分隔符). It then numbers(编号) and displays the strings,
one string to an output line.
1 // strfile.cpp -- read strings from a file 2 #include <iostream> 3 #include <fstream> 4 #include <string> 5 #include <cstdlib> 6 int main() 7 { 8 using namespace std; 9 ifstream fin; 10 fin.open("tobuy.txt"); 11 if (fin.is_open() == false) 12 { 13 cerr << "Can't open file. Bye.\n"; 14 exit(EXIT_FAILURE); 15 } 16 string item; 17 int count = 0; 18 19 getline(fin, item, ':'); 20 while (fin) // while input is good 21 { 22 ++count; 23 cout << count <<": " << item << endl; 24 getline(fin, item,':'); 25 } 26 cout << "Done\n"; 27 fin.close(); 28 return 0; 29 }
Here is a sample tobuy.txt file:
sardines:chocolate ice cream:pop corn:leeks:
cottage cheese:olive oil:butter:tofu:
Typically, for the program to find the text file, the text file should be in the same directory
as the executable(可执行) program or sometimes in the same directory(目录) as the project file. Or
you can provide the full path name. On a Windows system, keep in mind that in a C-style
string the escape sequence \\ represents a single backslash(反斜杠):
1 fin.open("C:\\CPP\\Progs\\tobuy.txt"); // file = C:\CPP\Progs\tobuy.txt
Note that with : specified as the delimiting character(分界符), the newline character becomes
just another regular character.Thus, the newline character at the end of the first line of
the file becomes the first character of the string that continues as "cottage cheese".
Similarly, the newline character at the end of the second input line, if present, becomes
the sole(唯一的) content of the ninth input string.
posted on 2015-04-24 20:07 chunlanse2014 阅读(182) 评论(0) 编辑 收藏 举报