1: // Filename: CPPSTR1.CPP 2: // Purpose: Illustrates C++ string objects: declaration, initialization, 3: // copying, concatenation, computing length, output with cout. 5: #include <iostream> 6: #include <string> 7: using namespace std; 9: #include "PAUSE.H" 11: int main() 12: { 13: cout << endl; 14: cout << "This program illustrates declaration, " 15: << "initialization, copying, concatenation, " << endl 16: << "and output with cout, of C++ strings. " 17: << "Study the source code while running it. " << endl; 18: cout << endl; 19: Pause(0); 21: // You can initialize a C++ string object in its declaration: 22: string s1 = "Hello, "; 23: string s2("world!"); // Note this method of initialization. 25: // You can also assign to a C++ string object after declaring it: 26: string s3; 27: s3 = "Hello, world!"; 29: // Now we print out the three strings and their lengths: 30: cout << "Length of \"" << s1 << "\" is " << s1.length() << "." << endl; 31: cout << "Length of \"" << s2 << "\" is " << s2.length() << "." << endl; 32: cout << "Length of \"" << s3 << "\" is " << s3.length() << "." << endl; 33: Pause(0); 35: string s4 = s1; 36: string s5; 37: s5 = s2; 38: s4 += s5; // Appends s5 to s4 and is equivalent to s4 = s4 + s5; 39: cout << s4 << "<<" << endl; 40: Pause(0); 42: // Note that an "assignment expression" actually 43: // returns the string value of the assignment. 44: cout << (s4 = "How are you?") << "<<" << endl; 45: cout << (s5 = "Fine!") << "<<" << endl; 46: Pause(0); 48: // Note that copying a shorter string to a longer string 49: // "does the right thing" and puts the '\0' in the right place. 50: cout << s4 << "<<" << endl; 51: s4 = s5; 52: cout << s4 << "<<" << endl; 53: Pause(0); 55: return 0; 56: }