Constructing a String
Table 16.1 string Class Constructors
Constructor | Description |
(#1) string(const char * s) | Initializes a string object to the NBTS pointedto by s. |
(#2) string(size_type n, char c) | Creates a string object of n elements, eachinitialized to the character c. |
(#3) string(const string & str) | Initializes a string object to the string objectstr (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 pointedto by s and continues for n characters, even ifthat exceeds the size of the NBTS. |
(#6) template<class Iter>string(Iter begin,Iter end) | Initializes a string object to the values in therange [begin, end), where begin and end actlike pointers and specify locations; the rangeincludes begin and is up to but not includingend. |
(#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 theend of str or using n characters, whichevercomes first. |
(#8) string(string && str) noexcept(C++11) | Initializes a string object to the string objectstr; str may be altered (move constructor). |
(#9) string(initializer_list<char> il)(C++11) | Initializes a string object to the characters inthe initializer list il. |
1 // str1.cpp -- introducing the string class 2 #include3 #include 4 // using string constructors 5 6 int main() 7 { 8 using namespace std; 9 string one("Lottery Winner!"); // ctor #110 cout << one << endl; // overloaded <<11 string two(20, '$'); // ctor #212 cout << two << endl;13 string three(one); // ctor #314 cout << three << endl;15 one += " Oops!"; // overloaded +=16 cout << one << endl;17 two = "Sorry! That was ";18 three[0] = 'P';19 string four; // ctor #420 four = two + three; // overloaded +, =21 cout << four << endl;22 char alls[] = "All's well that ends well";23 string five(alls,20); // ctor #524 cout << five << "!\n";25 string six(alls+6, alls + 10); // ctor #626 cout << six << ", ";27 string seven(&five[6], &five[10]); // ctor #6 again28 cout << seven << "...\n";29 string eight(four, 7, 16); // ctor #730 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 toby 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 #6Because the name of an array is a pointer, both alls + 6 and alls + 10 are typechar *, so the template is used with Iter replaced by type char *.The first argumentpoints to the first w in the alls array, and the second argument points to the space followingthe first well.Thus, six is initialized to the string "well". Figure 16.1 shows howthe 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 asthe 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 argumentto the constructor:string seven(&five[6], &five[10]);// ctor #6 againThe seventh constructor copies a portion of one string object to the constructed
object:string eight(four, 7, 16); // ctor #7This statement copies 16 characters from four to eight, starting at position 7 (theeighth 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 word3 cin.getline(info, 100); // read a line, discard(丢弃) \n4 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 word3 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 characters4 cin >> lname; // can read a very, very long word5 cin.getline(fname, 10); // may truncate(截断) input6 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 theistream class, whereas the string versions are standalone(独立的) functions.That’s why cin is aninvoking(调用) 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 removedfrom the input stream but not stored.3. The maximum possible number of characters (the lesser(较小的) of string::npos and thenumber of bytes in memory available for allocation) is read, in which case failbitof 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, youcan also use them for file input. Listing 16.2 shows a short example that reads strings fromthe file. It assumes that the file contains strings separated by the colon(冒号) character and usesthe 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 #include3 #include 4 #include 5 #include 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 good21 {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 directoryas the executable(可执行) program or sometimes in the same directory(目录) as the project file. Oryou can provide the full path name. On a Windows system, keep in mind that in a C-stylestring 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 ofthe 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, becomesthe sole(唯一的) content of the ninth input string.