C++ Reading from files assignment

Hi, I have an assignment that asks to Write a program for a professor who wants to track the number of students who pass, fail, or do not take the final. The information is kept in a file will contain a 1 for a student who passed, a 2 for a student who failed, and a 0 if the student did not take the exam. Keep track of the total number of students scores entered. You may use EOF or a sentinel value to signify the end of a file. Output the number of students who passed, failed, and did not take the exam. Calculate and print the percent of students who passed (# of students who passed/ total students). Use a function to calculate the percentage return the value to main(). Print the percentage in the main() function.

I have a little code right now, my problem is when I read my file I only get the first number from the file. So if someone could point me in the right direction that would help a lot! Thanks!
#include <stdio.h>
//Function Prototypes

//Main
int main(void){

FILE *inp; /* pointer to input file */
int grades;
int values;

/* Prepare files for input or output */
inp = fopen("/Users/PabloE/Downloads/UT/Progr/Source FIles/Lab03/Lab03/grades.txt", "r");

/* Input each item, format it, and write it */
values = fscanf(inp, "%d", &grades);
printf("The passing grades are %d\n", grades);
/* Close the files */
fclose(inp);
return (0);
You need to read the file inside a loop - like so:
1
2
3
4
while (fscanf(inp, "%d", &grades) == 1)
{
  // use grades
}
Thanks so much thomas, now I just need to figure out how to count the 1's, 2's and 0's inside the file :S
You need 3 vars to hold the count - like int pass_count, int fail_count and int not_taken_count set initially to 0.
When you read a number you increment to corresponding var.
Just give it a try.
Topic archived. No new replies allowed.