/* Filename: maketext.cpp Author: Br. David Carlson Date: February 1, 1998 Revised: June 5, 1998 Revised: July 13, 2000 to use modern headers. This program prompts the user for the name of a file to create. Then it asks the user to enter lines of text, which are written to that file. CTRL z is used to stop data entry. */ #include #include // needed for files using namespace std; const int MaxString = 120; typedef char StringType[MaxString]; /* Given: InStream An input file stream already 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; } /* Given: OutFile A file stream already opened for output. Task: To get lines of text from the user and write them to OutFile. Return: OutFile The modified file stream. */ void WriteToFile(fstream & OutFile) { StringType Line; cout << "Enter a line of text (or press CTRL z to quit):" << endl; MyGetLine(cin, Line, MaxString); while (! cin.fail()) { OutFile << Line << endl; cout << "Enter a line of text (or press CTRL z to quit):" << endl; MyGetLine(cin, Line, MaxString); } } int main(void) { StringType FileName; fstream OutFile; cout << "Enter the name of the text file to be created: "; MyGetLine(cin, FileName, MaxString); OutFile.open(FileName, ios::out); if (OutFile.fail()) { cerr << "Could not create file " << FileName << endl; exit(1); } WriteToFile(OutFile); OutFile.close(); // very important to close an output file return 0; }