Hello! In this program, I am allowing the user to input grades that will be written to a file. Afterward, I need to read from that file and determine the highest and lowest grades (as well as an average and so forth). I have been stuck on how to do this. I am completely unaware on how to set up a loop to read from the file and determine which number from the file is the highest or lowest. Can anyone help? Thanks!
We've only just went over loops over the past week or so. We aren't generally using things that make it easier on us. What you see in my code is generally what we have learned so far, other than something I was planning on using , while (inFile >> num) in order to constantly read from a file.
What I was thinking about was using a while loop to read from the file and have variables for highest and lowest as well as a number placeholder and determine if one variable is higher than another and assign the higher variable to that. But Every time I tried it, it wouldn't work..
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
usingnamespace std;
int main()
{
int userInput, userGrade, count = 1, userIn;
ofstream outFile;
outFile.open("data.txt");
cout << "How many scores would you like to read? : ";
cin >> userInput;
while (count <= userInput)
{
cout << "Enter your grade for assignment " << count << ": ";
cin >> userGrade;
outFile << "assignment " << count << " ";
outFile << userGrade << endl;
if (userGrade >= 0 && userGrade <= 100)
{
count++;
}
}
Here is what I am trying to do in order to find the Highest and lowest integers from the file. Note that I need to use getline in order to grab the information for the file, then grab the numbers from it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string whole;
int number, highest, lowest;
highest = 100;
lowest = 0;
inFile.open("data.txt");
while (inFile >> whole)
{
//I am lost here. I forgot that I have to use a string
// in order to grab the whole line, but I somehow
// need to be able to grab just the integer to store into number
}
inFile.close();
If you do know for certain that each line of input contains exactly one word and two integers, then you can read in that much:
1 2 3 4 5 6 7
string word;
int id;
int value;
while ( inFile >> word >> id >> value )
{
// use the data
}
An another option is to use stringstream:
1 2 3 4 5 6 7 8 9 10 11 12
string line;
while ( std::getline( inFile, line ) )
{
std::istringstream iss( line );
string word;
int id;
int value;
if ( iss >> word >> id >> value )
{
// use the data
}
}
PS. What is the point of having word "assignment" on every line of the file? It looks uselessly redundant.