3.2.2 Operations on strings
Along with defining how objects are created and initialized, a class also defines the operations that objects of the class type can perform. A class can define operations that are called by name, such as the isbn function of our Sales_item class (§ 1.5.2, p. 23). A class also can define what various operator symbols, such as << or +, mean when applied to objects of the class’ type. Table 3.2 (overleaf) lists the most common string operations.
Reading andWriting strings
As we saw in Chapter 1, we use the iostream library to read and write values of built-in types such as int, double, and so on. We use the same IO operators to read and write strings:
-
- int main()
- {
- string s;
- cin >> s;
- cout << s << endl;
- return 0;
- }

This program begins by defining an empty string named s. The next line reads the standard input, storing what is read in s. The string input operator reads and discards any leading whitespace (e.g., spaces, newlines, tabs). It then reads characters until the next whitespace character is encountered.
So, if the input to this program is Hello World! (note leading and trailing spaces), then the output will be Hello with no extra spaces.
Like the input and output operations on the built-in types, the string operators return their left-hand operand as their result. Thus, we can chain together multiple reads or writes:
- string s1, s2;
- cin >> s1 >> s2;
- cout << s1 << s2 << endl;
If we give this version of the program the same input, Hello World! , our output would be “HelloWorld!”
Reading an Unknown Number of strings
In § 1.4.3 (p. 14) we wrote a programthat read an unknown number of int values. We can write a similar program that reads strings instead:
- int main()
- {
- string word;
- while (cin >> word)
- cout << word << endl;
- return 0;
- }
In this program, we read into a string, not an int. Otherwise, the while condition executes similarly to the one in our previous program. The condition tests the stream after the read completes. If the stream is valid—it hasn’t hit end-of-file or encountered an invalid input—then the body of the while is executed. The body prints the value we read on the standard output. Once we hit end-of-file (or invalid input), we fall out of the while.