/* Filename: strings.cpp Author: Br. David Carlson Date: June 5, 1998 Revised: June 26, 2000; August 21, 2001 This program reads in a few strings from the keyboard and prints them on the screen. It also copies the last string and appends something to the end of it, printing out the results in both cases. Tested with: Microsoft Visual C++ 6.0 Microsoft Visual C++ .NET g++ under Linux */ #include // Most compilers say that you need cstring or a similar header in // order to use the strlen function. Visual C++ 6.0 seems to be // fine without including cstring, but g++ apparently needs it. #include using namespace std; const int MaxString = 12; typedef char StringType[MaxString]; int main(void) { StringType Message, MsgCopy; int Num; cout << "This program only handles strings up to length " << MaxString - 1 << endl << endl; cout << "Enter a string containing no spaces: "; cin >> Message; // get the newline so it doesn't go into Message below cin.get(); cout << Message << " was placed into the string." << endl << endl; cout << "Enter another string (spaces allowed): "; cin.getline(Message, MaxString); cout << Message << " was placed into the string." << endl << endl; cout << "Enter another string (spaces allowed): "; cin.getline(Message, MaxString); Num = strlen(Message); cout << Message << " was placed into the string." << endl; cout << "It contains " << Num << " characters." << endl << endl; strcpy(MsgCopy, Message); cout << "Copied message contains: " << MsgCopy << endl << endl; // Warning: strcat does no check to see if the copied characters // will fit on the end of the MsgCopy array. If there are too many // characters, strcat will blindly copy them past the end of the // array. This could overwrite other variables or other memory // areas used by your program, perhaps resulting in a runtime // error! Thus strcat is unsafe unless the programmer checks // first to see that there is sufficient room in the array. strcat(MsgCopy, "END"); cout << "Copied message with END appended: " << MsgCopy << endl << endl; return 0; }