minimal working version, lots of comments.
#include <fstream>
#include <iostream>
// this here's a function. it's a bit of code that accepts 3 parameters,
// does stuff with them, prints a message, then returns a value.
int computeGradeAverage(int a, int b, int c)
{
int avg = ( a + b + c ) / 3;
std::cout << "computed average of " << a << ", " << b << ", " << c << ", is " << avg << std::endl;
return avg;
}
// the main function. typically programs have many functions, and the C/C++
// languages (and java etc etc) require a single 'main' function to start the program at
// (it can be up top, or at bottom of file, or in the middle; doesn't matter).
int main()
{
// a) allocate named variable of given types to hold values.
int id;
int score1;
int score2;
int score3;
int gradeaverage;
std::ofstream output;
std::ifstream input;
// b) open input and output files
input.open("StudentInfo.txt");
output.open("studentGrade.txt");
// c) loop over each line of input file
do
{
// c.i) read data (one line) in
input >> id >> score1 >> score2 >> score3;
// c.ii) do calculation on input data
gradeaverage = computeGradeAverage(score1, score2, score3);
// c.iii) write data out
output << id << " " << gradeaverage << std::endl;
}
// d) stop looping if we have reached the end of the input file (eof = end of file)
// ... 'input' is the file object; input.eof() is call of one of its member function s
// ... the 'eof()' function will return true (if at end) or false (if there's more data).
// ... "while(!thing)" means "while NOT thing" .. so the 'while ( ! input.eof() )' means:
// .. do { "the things" } while " input file not finished "
while (!input.eof());
// There are several ways of doing this, like while(!eof) { .. } and others.
// e) close the files. while it'll work without doing this, it's a very important
// habit to put away things after use; deallocate memory, close files, commit transactions,
// free (as in liberate, not beer) any acquired resources, etc etc.
input.close();
output.close();
// f) return a value to the caller. In this case, the caller is the operating system,
// and at least with unixy programs, '0' means 'okay', and other numbers would mean
// some error occurred. For example, the 'g++' compiler returns 1, on any error.
return 0;
}