/* Filename: readform.cpp Author: Br. David Carlson Date: February 1, 1998 Revised: July 13, 2000 to use modern headers. This program prompts the user for the name of a file to read. This must be a formatted text file as created by the makeform program. It assumes that each product name consists of just one word of up to 40 characters. The data from the file is displayed on the screen. */ #include #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: InFile A file stream already opened for input. Assumes: That InFile is associated with a text file of the type described at the top of this program. Task: To read the data from InFile and display it on the screen. Return: InFile The modified file stream. */ void DisplayFile(fstream & InFile) { StringType ProductName; float Price; int Count = 0; InFile >> ProductName; while (! InFile.fail()) { InFile >> Price; InFile.get(); // read the newline and discard it cout << setw(40) << ProductName << setw(12) << Price << endl; Count++; if (Count == 22) { Count = 0; cout << " Press ENTER to go on..."; cin.get(); } InFile >> ProductName; } if (Count != 0) { cout << " Press ENTER to go on..."; cin.get(); } } int main(void) { StringType FileName; fstream InFile; cout << "Enter the name of the text file to be read: "; MyGetLine(cin, FileName, MaxString); InFile.open(FileName, ios::in); if (InFile.fail()) { cerr << "Could not open file " << FileName << endl; exit(1); } DisplayFile(InFile); InFile.close(); return 0; }