'Need help figuring out how to solve a c++ code problem
I am supposed to write a c++ program that reads a text.txt file named grades.txt, where the text file contains names and a grade next to it. The program is supposed to read the text file and determine what student has the highest grade and display the name of that student. I also cannot use any existing function such as search, find, etc. and I cannot use any arrays or multidimensional data types. I was able to figure out how to open the text file (and make sure it opened successfully) and I also know that I need a while loop maybe?? This is all I have right now. Any idea on how I can do this??
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int grade;
string name;
ifstream fin;
fin.open("grades.txt");
if (fin.is_open())
{
while (fin >> grade && fin >> name)
{
if
}
}
else
{
cout << "failed to open file!" << endl;
return -1;
}
}
Example of data file.(the name with each grade is in a separate line in the file)
Velma 56
Linda 83
John 89
Isaac 75
Maggie 90
Seth 41
June 96
Hunter 100
Solution 1:[1]
Here's a sample of the inner loop:
std::string student_name;
int grade;
//...
int highest_grade;
std::string student_highest_grade;
my_file >> highest_grade >> student_highest_grade;
while (my_file >> grade >> student_name)
{
if (grade > highest_grade)
{
highest_grade = grade;
student_highest_grade = student_name;
}
}
You were proceeding nicely. I filled in your if statement for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas Matthews |
