class - a datatype to define an object.
object - a variable storing an instance of a class. An object is a special kind of variable that
is like a package containing many things inside. It has multiple values inside it, and it also can have
functions as part of it. These functions are called member functions.
To work with file i/o we need to include the fstream library with the statement:
#include <fstream>
This allows us access to the ifstream class for input from a file, and the ofstream class for output to a
file. We declare an input file stream object with the following statement:
ifstream file_in;
Then we open the file:
file_in.open("scorefile.txt"); // Your filename here
Once a file stream is open we use it in much the same way as we use cin and cout. So to input a value
from a file that is whitespace-delimited, we write:
double one_score;
file_in >> one_score;
Or to input the next character including whitespace or anything else, we write:
char c;
file_in.get(c);
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ofstream out_stream;
double num1, num2, num3;
cout << "Please enter three numbers separated by spaces: ";
cin >> num1 >> num2 >> num3;
// create and open a file called "output_file.txt" for output:
out_stream.open("output_file.txt");
// standard "fixed" notation instead of scientific notation,
// also making "precision" below set number of digits after
// the decimal point, not significant digits:
out_stream << fixed;
// show all specified digits after decimal, even if 0's:
out_stream << showpoint;
// show 2 digits after decimal for floating pt. numbers:
out_stream << setprecision(2);
// Output num1 in a width of 6 characters
// (right-aligned by default):
out_stream << setw(6) << num1 << endl;
// and the same with num2 and num3:
out_stream << setw(6) << num2 << endl;
out_stream << setw(6) << num3 << endl;
// close the output file:
out_stream.close();
return 0;
}
/* Sample Output:
bash-2.04$ a.out
Please enter three numbers separated by spaces: 1 25.2 198.87634
bash-2.04$ cat output_file.txt
1.00
25.20
198.88
*/
char class_title[81];
cout << "Enter name of class";
cin.getline(class_title, 81);
// Exact user entry, up to newline or 80th character
// will be stored in class_title. e.g. "Intro. to Programming in C++"
nameAverage.cpp: Solution to above in-class exercise averaging grades