Files

The program asks the user to enter 5 numbers. The total is calculated and displayed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Read in 5 numbers, find the total 
#include<iostream>
using namespace std;
int main() { 
  double num,total=0; 
  int i;
  for (i = 0; i<5; i++) { 
   cout<<"Enter a number:";
   cin>>num;
   total+=num;
  } //for loop
  cout<<"total="<<total<<endl;
  system("pause");
  return 0;
} //main
CODE

We would like to create a file that shows a copy of what was seen on the console.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//Read in 5 numbers, find the total, echo to file 
#include<iostream>
#include<fstream>
using namespace std;
int main() { 
   bool outok=true;
   ofstream out; //output file stream 
   out.open("c:/mycpp/numbers.txt"); //associates the name inch with a file 
   if (out.fail()) //maybe the location doesn't exist, or it is full, or protected 
      outok=false; 
   double num,total=0; 
   int i;
   for (i = 0; i<5; i++) { 
      cout<<"Enter a number:";
      cin>>num;
      if(outok) out<<"Enter a number:"<<num<<endl; //mimic what is on console
      total+=num;
   } //for loop
   cout<<"total="<<total<<endl;
   if(outok) {
      out<<"total="<<total<<endl;
      cout<<"Output file created\n";
      out.close();
   }
   system("pause");
   return 0;
} //main
CODE

console

Please note: A variable outok is initially set to true. If we can't open the file, it is set to false (line 10). We do not try to write to the file if outok is false (lines 16 and 21.)

NEXT: Functions