/* Filename: string.cpp Author: Br. David Carlson Date: July 10, 1999 Last Revised: March 24, 2003 This program initializes and prints a few strings just to show some of what can be done with the string container class. How to convert between char array strings and objects of the string class is also shown. Tested with: Microsoft Visual C++ 6.0 Microsoft Visual C++ .NET g++ under Linux */ #include #include using namespace std; const int StrMax = 80; typedef char ShortString[StrMax]; int main(void) { string MsgA, MsgB("Hello, world!"), MsgC; ShortString MsgCharArray; int k; cout << MsgB << endl; MsgA = MsgB + " How are you?"; cout << MsgA << endl; MsgA = MsgB + '!'; cout << MsgA << endl; for (k = 0; k < 5; k++) cout << MsgA[k]; cout << endl << endl; // If we want a copy of MsgA put into a char array string we can do this: // Note that the c_str function returns a pointer to a constant char array. strcpy(MsgCharArray, MsgA.c_str()); // Somewhat dangerous: assumes it fits! cout << "Char array string contains: " << MsgCharArray << endl << endl; // It is easier to go the other way, to copy a char array into a string object: MsgC = MsgCharArray; cout << "String object copy of this: " << MsgC << endl; return 0; }