/* Filename: makeform.cpp Author: Br. David Carlson Date: February 1, 1998 Last Modified: February 21, 2013 This program prompts the user for the name of a file to create. Then it asks the user to repeatedly enter the name of a product and its price. This data is written to a text file having the name that the user specified. CTRL z is used to stop data entry. (Substitute CTRL d in Linux.) Tested with: Microsoft Visual C++ 2008 g++ under Linux */ #include #include // needed for files using namespace std; const int MaxString = 120; typedef char StringType[MaxString]; void WriteToFile(fstream & OutFile); int main(void) { StringType FileName; fstream OutFile; cout << "Enter the name of the text file to be created: "; cin.getline(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; } /* Given: OutFile A file stream already opened for output. Task: To repeatedly get a product name and price from the user and write them to OutFile. Return: OutFile The modified file stream. */ void WriteToFile(fstream & OutFile) { StringType ProductName; float Price; // change to CTRL d for Linux: cout << "Enter a product name (or press CTRL z to quit):" << endl; cin.getline(ProductName, MaxString); while (! cin.fail()) { cout << "Enter the price of this product:" << endl; cin >> Price; cin.get(); // read in the newline and discard it OutFile << ProductName << ' ' << Price << endl; // change to CTRL d for Linux: cout << "Enter the product name (or press CTRL z to quit):" << endl; cin.getline(ProductName, MaxString); } }