Handout 4

Review of Files

 

1. Open a project, and a .cpp file.

2. Choose File, New from the menu and choose Text File.  Once the text file is opened, go to the File menu again and choose the option that says “move” into the project. Your text file should show in the Solution Explorer Window.

3. Copy the following into your text file.

5

6

-9

22

3

 

4. Copy the following code into your source code.

 

#include<iostream>

//header file needed for files

#include<fstream>

using namespace std;

 

int main()

{

      //program to add numbers from a file

     

      //declarations for file stream variables

      ifstream inFile;

      ofstream outFile;

 

      //declarations for other variables

      int total = 0;

      int inputVal;

 

      inFile.open("data.txt"); //put the name of your text file in the quotes

 

      outFile.open("out.txt"); //this file will be created when the program runs

 

      //read from the file

      inFile >> inputVal;

     

      //do the loop while there are still numbers in the file

      while (!inFile.eof())

      {

            total += inputVal;

            inFile >> inputVal;

 

      }

 

      //output to the standard output and to a file

      cout << "The total is: "<< total << endl;

      outFile << "The total is: " << total << endl;

 

      //close files

 

      inFile.close();

      outFile.close();

 

      return 0;

 

}

 

5. Run your code. What is the output?

 

6. Change your code so that it only adds the positive numbers in the file.

 

7. Change your code so that the main function only opens the files, calls a function that sums the numbers, and closes the file.