You are here:

C++/I am confused with my program


I am trying to write a program that will read students names and 3 grades from a file. then the 3 grades are averaged rounded to 1 decimal place.
after that i have to modify the program so it can read the output for 10 students, and then modify it again so it can process information from an uknown number of students.

Hello Alejandra

You have not told me what part of your program is giving you trouble. I will give you a bit of code to get you started, and I'll give you instructions about how to continue after that.

For this I'm going to assume that each student has three grades. If each student has a variable number of grades, then it gets more complicated.

You need to open an input file with ifstream, and read in the name and marks with the input operator (>>)

My student.txt file looks like this and is located in the same directory as the program.
StudentA 55 65 75

Here is the program. It prints out what it reads in.

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(void)
       ifstream fin("Students.txt");
       std::string name;
       int mark1;
       int mark2;
       int mark3;

       fin >> name >> mark1 >> mark2 >> mark3;
       cout << name << ' ' << mark1 << ' ' << mark2 << ' ' << mark3 << endl;

       return 0;

To read in 10 students, or an unknown number of students, you need a loop, and you need to check if you have gone past the end of the file. To check if you have gone past the end of the file, you should use the ifstream::eof() method after every item you read. If fin.eof() is true, the program is done. If you can assume that each line in the file is a student with three grades, then you only need to check for end of file after reading the name.

Does that make sense ?

You can read more about ifstream in your help system or at

Show me an attempt at calculating the average and at looping through the file and I'll be happy to help you more.

Best regards


All Answers

Answers by Expert:

Ask Experts




No longer taking questions.


No longer taking questions.

No longer taking questions.

©2016 All rights reserved.