Cout array members by one int identifer member

So I have a array of structs with members firstName, lastName, and testScore read in from a text file. I need to set a max grade, or highest grade, from the testScore data. How would I do this and be able to identify the firstName and lastName of the student with the highest grade?

In other words, how can I cout array members of a certain element of an array by identifying which element has the highest testScore member?

 
  
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;




struct studentType {

string firstName;
string lastName;
int testScore;
char Grade;
int Max;

};

studentType students[20];



void getStudentInfo() {
ifstream inputFile;
inputFile.open("StudentData.txt");

for (int i = 0; i < 20; i++)
inputFile >> students[i].testScore >> students[i].firstName >> students[i].lastName;
}


void setGrade() {
for (int j = 0; j < 20; j++)
{
if ((students[j].testScore >= 90) && (students[j].testScore <= 100))
students[j].Grade = 'A';

else if ((students[j].testScore >= 80) && (students[j].testScore <= 90))
students[j].Grade = 'B';

else if ((students[j].testScore >= 70) && (students[j].testScore <= 80))
students[j].Grade = 'C';

else if ((students[j].testScore >= 60) && (students[j].testScore <= 70))
students[j].Grade = 'D';

else if ((students[j].testScore >= 0) && (students[j].testScore <= 59))
students[j].Grade = 'F';

}
}

void printResults() {

cout << "Student Information" << endl;
cout << endl;

for (int i = 0; i < 20; i++)
cout << students[i].lastName << ", " << students[i].firstName << " " << students[i].testScore << " " << students[i].Grade << endl;


}

void declareWinner() {
for (int i = 0; i < 20; i++)
{
if (students[i].testScore > students[i].Max)
students[i].Max = students[i].testScore;


}


cout <<

}
int main()
{
getStudentInfo();
setGrade();
declareWinner();




printResults();






return 0;
}

You can iterate through the array, find the index of the one that you want, and then write it out...

biggest = 0;
for(dx = 0; ... etc all the array)
{
if (array[dx].something > array[biggest].something)
biggest = dx;
}

cout << array[biggest].fields ;

To find the student with the highest score you can use std::max_element.
To use this algorithm you need to implement either the < operator for studentType or use a lambda function.
Here is how to use the first option:
1
2
3
4
bool operator < (const studentType& s1, const studentType& s2)
{
  return s1.testScore < s2.testScore;
}

http://www.cplusplus.com/reference/algorithm/max_element/
Topic archived. No new replies allowed.