More C++ Answers
Question Library
Ask a question about C++
Volunteer
Experts of the Month
Expert Login
Awards
About Us
Tell friends
Link to Us
Disclaimer
|
| |
|
|
| |
| | | |
About Zlatko
Expertise I can answer questions about C / C++ programming, software design, algorithms, and interprocess communication. I have access to Microsoft Visual Studio and gcc as my development platforms.
If I'm maxed out here, try me in the C category.
Experience I have been developing software professionally in C and C++ for UNIX and Microsoft Windows since 1991.
Education/Credentials I have a Bachelor of Applied Science in Computer Engineering from the University of Waterloo located in Waterloo, Ontario, Canada. I hold the IEEE Certified Software Development Professional designation and SUN Java Programmer and Java Developer credentials.
| | |
| |
You are here: Experts > Computing/Technology > C/C++ > C++ > I am confused with my program
C++ - I am confused with my program
Expert: Zlatko - 10/28/2009
Question 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.
Answer 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
http://www.cplusplus.com/reference/iostream/fstream/
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
Zlatko
Add to this Answer Ask a Question
|
|