MCC - Marquez - CIS162AB - C++ Level I
P08_ex An Example of File Processing
   cpp.gif

The purpose of this C++ programming example is to familiarize students with file processing. The example includes the creation of a new file, writing to the file, and reading the file.

Sample Output for P08_ex:

P08ex   Juan Marquez

Enter the letter of the desired menu option.
Press the Enter key after entering the letter.

  A: Create a new file for Student Information
  B: Enter Student Information
  C: List Student Information

  X: Exit the Student Information Module

Choice: A

P08ex   Juan Marquez    Create new file for Student Information

Creating a new file will delete any existing information.
Do you want to proceed with creating a new file? (Y/N) y

  New file created successfully!

Procedure completed. Press Enter to continue:

--
Choice: B

P08ex   Juan Marquez    Enter Student Information

  Enter the Student Id and Test Score:

  3040  89

    Would you like to add another student? (Y/N) y
  Enter the Student Id and Test Score:

  3042  92

    Would you like to add another student? (Y/N) y
  Enter the Student Id and Test Score:

  3044  84

    Would you like to add another student? (Y/N) n

Procedure completed. Press Enter to continue:

--
Choice: C

P08ex   Juan Marquez    List Student Information

Student   Score

  3040      89
  3042      92
  3044      84

Procedure completed. Press Enter to continue:

--
Choice: X

Now exiting Student Information...please wait.



Source Code:

//P08ex File Processing   Juan Marquez  
/*
   This program allows users to enter and save student information to a file.
   The file can then be read so that the information entered can be displayed.
   Instructors can choose from the following menu options:
   
     A: Create a new file for Student Information
     B: Enter Student Information
     C: Display Student Information 

     X: Exit the Student Information Module
     
   The following items for each student are saved in the file p08ex.txt:
     Student ID  
     Test Score

*/
#include <fstream>  // file processing
#include <iostream> // cin and cout
#include <cctype>   // toupper
#include <iomanip>  // setw

using namespace std;

//menu options
//Opt A: 
void createNewFile();

//Opt B: 
void enterInfo();

//Opt C:    
void listInfo();

//Supporting functions
void displayContinuePrompt();


//Program starts here   
void main()
{
//Declare local variable to store menu option selected
    char   choice;

//Check to see what the user wants to do
    do  //while (choice != 'X')
    {
        cout << "P08ex   Juan Marquez    \n\n";

        cout << "Enter the letter of the desired menu option. \n"
             << "Press the Enter key after entering the letter. \n\n"

             << "  A: Create a new file for Student Information  \n"
             << "  B: Enter Student Information  \n"
             << "  C: List Student Information   \n\n"

             << "  X: Exit the Student Information Module \n\n"

             << "Choice: ";

        cin >> choice;
        cout << "\n\n";

        choice = toupper(choice); //convert to uppercase

        switch (choice)
        {
            case 'A':
                createNewFile();
                break;
            case 'B':
                enterInfo();
                break;
            case 'C':
                listInfo();
                break;

            case 'X':
                cout << "Now exiting Student Information...please wait.\n\n";
                break;
            default:
                cout << "\a"; //alert
                cout << "Invalid Option Entered - Please try again. \n\n";

        }//end of switch

    } while (choice != 'X');

    return; 
}//end of main


//Function Definitions
void createNewFile()
{
//Declare local variables
    char answer;

    cout << "P08ex   Juan Marquez    Create new file for Student Information \n\n";

//Prompt the user if they want to create a new file
    cout << "Creating a new file will delete any existing information. \n";
    cout << "Do you want to proceed with creating a new file? (Y/N) ";
    cin >> answer;

//If Yes, try to create a new file using open function
    if (toupper(answer) == 'Y')
    {
//  Open the file for output 
        ofstream fileOut;
        fileOut.open("p08ex.txt");
//  If there are any errors, display an error message and return.
        if (fileOut.fail())
        {
            cout << "\n  Error: Output file could NOT be created. ";
            displayContinuePrompt();
            return;
        }
//   else display message that a file was created successfully
        cout << "\n  New file created successfully! ";
//   Close the file
       fileOut.close();
    }
    else
//else display a message that a new file was NOT created
    {
        cout << "\n  New file NOT created.";
    }
//Call displayContinue to pause
    displayContinuePrompt();

    return;
}

void enterInfo()
{
//Declare local variables
    int studentId;
    int testScore;
    char answer;

    cout << "P08ex   Juan Marquez    Enter Student Information \n\n";

//Open the file for output (append) 
    ofstream fileOut;
    fileOut.open("p08ex.txt", ios::app);
//If there are any errors, display an error message and return.
    if (fileOut.fail())
    {
        cout << "  Error: Output file NOT found. ";
        displayContinuePrompt();
        return;
    }

//Set output to 2 decimal positions for file
    fileOut.setf(ios::fixed);
    fileOut.setf(ios::showpoint);
    fileOut.precision(2);

//Use a do-while loop to get input
    do
    {
//  Display prompt and get the data
        cout << "  Enter the Student Id and Test Score: \n\n  ";
        cin >> studentId >> testScore;

//  Write data to file and format using setw manipulators
        fileOut << setw(6) << studentId;
        fileOut << setw(6) << testScore;
        fileOut << endl;

//  Prompt user if they want to add another student
        cout << "\n\n    Would you like to add another student? (Y/N) ";
        cin >> answer;
//  Do loop again if they don't enter N
    }while (toupper(answer) != 'N');
    
//Close the file
    fileOut.close();
//Call displayContinue to pause
    displayContinuePrompt();
    return;
}


void listInfo()
{
//Declare local variables
    int studentId;
    int testScore;

    cout << "P08ex   Juan Marquez    List Student Information \n\n";

//Open the file for input  
    ifstream fileIn;
    fileIn.open("p08ex.txt");
//If there are any errors, display an error message and return.
    if (fileIn.fail())
    {
        cout << "  Error: Input file NOT found. ";
        displayContinuePrompt();
        return;
    }


//Set output to 2 decimal positions for cout
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

//Display headings
    cout << "Student   Score \n\n";

//Read the first record. 
    fileIn >> studentId >> testScore;

//Use while loop to process file, because 
//  while loops handle empty files.
    while (! fileIn.eof())
    {
//  Display record read and format using setw manipulators
        cout << setw(6) << studentId;
        cout << setw(8) << testScore;
        cout << endl;

//  Read next record
        fileIn >> studentId >> testScore;
    }
    
//Close the file
    fileIn.close();
//Call displayContinue to pause
    displayContinuePrompt();

    return;
}

void displayContinuePrompt()
{
//Declare local variables
    char prompt;

    cout << "\n\nProcedure completed. Press Enter to continue: ";
    cin.ignore();
    prompt = cin.get();

    system("cls");   //clear screen - DOS

    return;
}
//End of program


Revised: 12/15/2006 - www.mc.maricopa.edu/~marquez/cis162ab/p08_ex_file_processing.html