Code:
char temp[5]; // Buffer to hold data that is read from the file
char gender; // Specifies if the data applies to males or females, ie m or f
double nFemaleGPA = 0, nMaleGPA = 0; // Holds the GPA for males and females
UINT32 nFemaleNum = 0, nMaleNum = 0; // Counter of how many times GPA has been read from the file for male/female
temp[4] = '\0'; // C strings always end with \0 and string functions expect it to, so let's add one to the end.
FILE* f = fopen("indata.txt", "r"); // Open indata.txt for reading, text mode
if (f == NULL); // Failed to open file - figure out why and toss our an error or something
for(;;) // Loop indefinetly
{
fread(temp, 4, 1, f); // Read 4 bytes from indata.txt, store in buffer temp
if ( feof(f) ) break; // If we've reached the end of the file, break out of the loop
gender = temp[0]; // Take the first character read from the file and put it into the gender varaible. Should be m or f.
fread(temp, 4, 1, f); // Read 4 more bytes from the file and store in temp
if (gender == 'm') // If the gender is male
{
nMaleGPA += strtod(temp); // Convert the contents of temp (the 4 read bytes which should be a number) to a double and add to nMaleGPA
nMaleNum++; // Increase the male entries counter by 1
}
else if (gender == 'f') // If the gender is female
{
nFemaleGPA += strtod(temp); // Same as above
nFemaleNum++;
}
}
fclose(f); // Close file
nFemaleGPA /= nFemaleNum; // Average GPA. Divide the total GPA by the number of entries found in the file.
nMaleGPA /= nMaleNum; // Average GPA
char gendertodisplay;
for(;;)
{
cout << "Enter gender to show data for. Male (m) or Female (f):"; // Ask for gender to display
cin.get(gendertodisplay, 1); // Get one character from the standard input
if (gendertodisplay != 'm' && gendertodisplay != 'f') cout << "Invalid gender specified! Try again!\n"; // If the user didn't type m or f, then print error message
else break; // If the user DID type m or f, then break the loop and continue
}
char ToDisplay[1000];
if (gendertodisplay == 'f') // If user chose female gender
vsprintf(ToDisplay, "Average female GPA: %0.3f.", nFemaleGPA); // Copy a formated string to ToDisplay.
else if (gendertodisplay == 'm') // If user chose male gender
vsprintf(ToDisplay, "Average male GPA: %0.3f.", nMaleGPA);
cout << ToDisplay;
This code should do, then. I find it very simple. Also take a look at vsprintf in the docs to see how it works. This will print the GPA in XX.YY.