// str3.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // // This program illustrates more of the C++ string type. In specific, the program // illustrates how the two string types (the C-Style and the C++ string) can be mapped // to each others. // // In general, mapping from a C-Style string to C++ string is straightforward. However, // the reverse conversion is not implicitly supported. C++ string is actually an array // of characters (not a variable pointer to a character); that is why const is enforced here. // The program clearly explains what is meant by that. // // Key Points: 1) Standard C++ string type // 2) C-Style strings // 3) Conversions between C++ and C-Style strings // 4) The c_str() method #include #include using namespace std; int main() { char *cs1 = "Converted from", *cs2 = " a C-Style string."; // Two C-Style strings char* cs3 = ", "; // A usual C-Style string char* cs4; string s1 = cs1; s1 += cs2; cout << "s1 is: " << s1 << endl; string s2 = "Hello", s3 = "there.", s4; // s4 is an empty string if (s4.empty()) { cout << "\ns4 is empty; will perform some string operations.\n"; s4 = s2 + cs3 + s3; // The following will simply display s4 cout << "\ns4 is: "; for (int i = 0; i < s4.size(); i++) cout << s4[i]; } // Now try to convert from C++ string to a C-style string // The following line will not compile. Un-comment it out and try. why? // c_str() returns a pointer to a constant array in order to prevent the // array from being manipulated. // cs4 = s1.c_str(); // As a result, the following is what we need to do const char* cs5 = s1.c_str(); cout << "\n\ncs5 is: " << cs5 << endl; cout << "Well, it is actually converted from C++ string!\n"; cout << endl; return 0; } /* The output s1 is: Converted from a C-Style string. s4 is empty; will perform some string operations. s4 is: Hello, there. cs5 is: Converted from a C-Style string. Well, it is actually converted from C++ string!! */