/* Filename: maketext.cpp Author: Br. David Carlson Date: February 23, 1998 Modified: July 4, 1998 Modified: July 16, 2000 to use modern headers. This program creates a text file of parts information. The data for each part consists of an ID number, number in stock, price, and description, and is read from the keyboard and written to this text file, called parts.txt. Each piece of data is written on a new line. Thus it takes 4 lines to hold the data for one part. */ #include // needed for files #include "parts.h" // needed for PartType const int MaxString = DescripMax; 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: fs A text file stream already opened for output. Task: To read parts data from the user, writing each piece of accumulated data to fs. Return: fs The modified file stream. */ void WriteToFile(fstream & fs) { int Number; PartType Part; cout << "Enter a part number (or 0 to exit): "; cin >> Number; while (Number != 0) { // Place data into the Part record: Part.ID = Number; cout << "Enter number in stock: "; cin >> Part.NumInStock; cout << "Enter price: "; cin >> Part.Price; cin.get(); // input newline at end of price cout << "Enter description: "; MyGetLine(cin, Part.Descrip, DescripMax); // Write the data from the Part record to the file, one field // at a time. Note that we cannot write the whole record to the // file (without overloading >> to handle these records). Also // note that instead of storing the data in the Part record, the // 4 items could be placed in 4 variables and each of them written // to the file. The text file itself thus contains just lines // of text; it does not contain records of data. fs << Part.ID << endl << Part.NumInStock << endl << Part.Price << endl << Part.Descrip << endl; cout << "Enter a part number (or 0 to exit): "; cin >> Number; } } int main(void) { fstream PartFile; PartFile.open("parts.txt", ios::out); if (PartFile.fail()) { cerr << "Could not create file parts.dat" << endl; exit(1); } WriteToFile(PartFile); PartFile.close(); return 0; }