Reputation: 99
The following program is supposed to ask the user how many students he wants to grade then have the user input the grades and get the average.
#include <stdio.h>
#include <stdlib.h>
struct person {
char Name[100];
int ID;
int Age;
double Score;
};
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
int size;
printf("How many students are you grading?(Not more than 100)-->");
scanf("%d",&size);
struct person *student;
double total=0,i=0, average;
student= malloc(sizeof(struct person));
//struct person student;
printf("Enter the following information:\n");
while (i<size) {
printf("%lf\n%lf\n",total,i);
printf("\n");
printf("Name:");
scanf("%s",student->Name);
printf("ID:");
scanf("%d",&student->ID);
printf("Age:");
scanf("%d",&student->Age);
printf("Score:");
scanf("%lf",&student->Score);
total = total + student->Score;
i++;
}
The code works fine until it needs to print out the average based on user input, at which point the program terminates without giving the average nor an error message.
if(size==1){
average = total / size;
printf("Class average is %0.2lf\n", average);
}
else
{
average=total/i;
printf("Class average is %0.2lf\n", average);
}
return 0;
}
Upvotes: 0
Views: 489
Reputation: 740
Most console programs are intended to be run from some kind of console host like windows cmd, where the output stays there and it would be annoying for user to do some additional work to end the program so they can run another command, but since you are just testing it, you should put some code at the end to wait for some user input, now there are many ways to do that like: getch(), getchar(), scanf("%*c"), system("pause") so you can try those, but some compilers do this automatically in debug mode, sometimes you just need to specify the behaviour in your IDE settings.
Upvotes: 2
Reputation: 51
I think the problem you are having is that the console is closing before you can read the average.
You could add:
getchar();
Before you return 0; in int main.
Upvotes: 0