Hello guys i'm kinda new to programming and i'm trying to do a certain task.
I want to use a for loop to read certain data from a txt file and print them to a console.
I'm trying to read student names and their grades.
something like
3 // 3 represents the number of students.
George 97
Sarah 70
Maya 88
the data may vary but it's always in this format.
any help is appreciated
thanks
yes in fact i know all about fstreams like ifstreams and ofstreams
i just need a way to extract strings from the input file
and then extract numbers
thanks
okay there are 3 names in the file
so i have to do this 3 times
then i need to compare the data to figure out which grade is higher
how might i do that?
Use struts or std::pait to tie name and grade together. Use vector to store data. Use loops to read data n times. Use loops and comparsion operators or standard library algorithm to determine high grade.
i'm not supposed to use struts or std::pait or vector
I'm supposed to use a for loop
i should first read the number at the top to determine the number of students.
i should then read the name alone then the number next to it
then go to the next line and do the same
and the next one.
how can i do that?
a) read in the number of students
b) declare two arrays, one for student name and the other for grade using 'new' and the number from a)
c) read in the students:
for ( each student i )
input >> name[i] >> grade[i];
i'm not supposed to use struts or std::pait or vector
I'm supposed to use a for loop
It is like saying "I am not supposed to use water, I am supposed to use sugar to make tea"
Pseudocode:
set highest_name to empty string and highest_grade to 0
read number of entries it NUM
loop NUM times
read current_name and current_grade
if current_grade is larger than highest_grade
set highest_name to current_name and highest_grade to current grade
end loop
guys also when I try to read a number
it reads it and then when i print to the console the number comes out as -858996430
also when i try to read strings the console prints blank
no the instructor asked for a for-loop
anyway
ireached this code yet when i run it it gives the number 'n' as -858996430 which ruins the code since i need it to read the first number in the file so that i can use it in the loop
any help?
int main()
{
int n;
int i=0;
int MaxGrade=0;
int CurrentGrade,LowestGrade;
LowestGrade=100;
string MaxName,CurrentName;
string LowestName;
ifstream input;
input.open("grades.txt");
input>>n;
The senseless value of n is usually sign of failed read. Check if file was properly open before reading:
1 2 3 4 5 6
std::ifstream input("grades.txt");
if(!input.is_open()){
std::cerr << "Error opening file\n";
std::exit(-1);
}
//Rest of the code
Additionally you should not manipulate n inside loop. It will lead to skipping some inputs. Get rid of else branches.
You should not read data twice on a single iteration. You shoul read once and then compare that data with both highest and lowest grade.