Reputation: 1
Im making a function for a basic program yet when I call it it does not utilize the do trap loop error conditions properly.
im calling it in the program like so....
for (x = 0; x < num_grades; x++)
{
do
{
get_grade(grade, x, name);
if (grade < 0 || grade > 100)
printf ("*** Invalid entry. Grade must be 0 to 100.\n");
} while (grade < 0 || grade > 100);
The function itself looks like this...
int get_grade (int grade, int i, char name[][25]) // A function to get grades //
{
char c;
int grade_get;
printf ("Enter grade #%i for %s: ", i+1, name[i] );
scanf ("%i", &grade);
while ( (c = getchar() != '\n') && c != EOF);
return grade_get;
}
I have prototyped it like so...
int get_grade (int, int, char [][25]);
I tried putting the error conditions in the function but it doesn't work with the for loop properly unless I did it wrong.
I know the code is inefficient but this is for a college class so we are only allowed to use what we learned and this is about the extent we learned. We haven't learned pointers or strcopy or anything like that so while it may be basic I don't have a choice :/
Thank you for your time and I appreciate any and all help :)
Upvotes: 0
Views: 30
Reputation:
grade_get
variable is not initialized so the function returns an undefined value.grade
either has to be a pointer or you can return the value (like I did)i
in the function it would be even cleaner.getchar()
returns an int so change type of c
to int
.get_grade()
. This simplifies main()
.#include <stdio.h>
int get_grade (int i, const char *name) {
int grade;
for(;;) {
printf ("Enter grade #%i for %s: ", i+1, name);
scanf ("%i", &grade);
int c;
while ( (c = getchar() != '\n') && c != EOF);
if (grade >= 0 && grade <= 100)
return grade;
printf ("*** Invalid entry. Grade must be 0 to 100.\n");
}
}
int main(void) {
const char names[][25] = {
"bob",
"bjork",
"jane"
};
for (size_t x = 0; x < sizeof(names) / sizeof(*names); x++) {
int grade = get_grade(x, names[x]);
}
}
and here is an example run:
Enter grade #1 for bob: -1
*** Invalid entry. Grade must be 0 to 100.
Enter grade #1 for bob: 0
Enter grade #2 for bjork: 101
*** Invalid entry. Grade must be 0 to 100.
Enter grade #2 for bjork: 100
Enter grade #3 for jane: 42
Upvotes: 1