/* Filename: strings.cpp Author: Br. David Carlson Date: June 5, 1998 Revised: June 26, 2000 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. */ #include using namespace std; const int MaxString = 12; typedef char StringType[MaxString]; /* Given: InStream An input file stream open for reading. StringMax The maximum number of characters that can be put into String, including the NULL that marks the end of the string. Task: To read up to StringMax - 1 characters from InStream, storing them in String, but stopping if a newline is read or end of file or an error condition is reached. Return: String The string just read, with a NULL appended to mark the end of the string. If a newline was read, it is not stored in String. The number of characters read into String (not counting the NULL) is returned in the function name. */ int MyGetLine(istream & InStream, char * String, int StringMax) { char Ch; int Count, Last; Count = 0; Last = StringMax - 1; Ch = InStream.get(); while ((Ch != '\n') && (! InStream.fail())) { if (Count < Last) String[Count++] = Ch; Ch = InStream.get(); } String[Count] = NULL; return Count; } int main(void) { StringType Message, MsgCopy; int Num; cout << "Enter a string: "; 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: "; MyGetLine(cin, Message, MaxString); cout << Message << " was placed into the string." << endl << endl; cout << "Enter another string: "; Num = MyGetLine(cin, Message, MaxString); 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; strcat(MsgCopy, "END"); cout << "Copied message with END appended: " << MsgCopy << endl << endl; return 0; }