Still working on my first homegrown C program design . The function basically allows the user to enter a list of classes and grades and saves the list to a file to be used later in the file. The function compiles and runs through without error except for the fact that it always prints the last user entry to the *profilep file twice. Just as a note, the scanchar function is one I made to scan in one character and an end of line character to throw away the end of line char before I learned about %*c about 30 minutes ago...
Also I haven't much bothered to strengthen the function against crazy user input but I have heard using fgets and sscanf in conjunction can replace scanf and protect against weird user input. If anyone could show me roughly how to apply this within the program it would be much appreciated. Thanks!
Here is the code, this is my first attempt to print code on here so bear with me
Code:
// creates a new profile and prints it to the profile file.
void newprof(FILE* profilep, const char *allclasses[ABBR_SIZE]){
int c, checker, counter;
int i, a;
char prof[MAX_PROF][ABBR_SIZE];
char grades[MAX_PROF][3];
char inchar, junk;
printf("Please enter the abbreviation of a class you have completed followed with your letter grade for that class and press enter.\n For example, ee161 c+ <enter> or me102 a- <enter>\n Please enter all characters as lowercase.\n");
// outer for-loop for inputting each class into the profile
for(c = 0; c < MAX_PROF; c++){
checker = 0;
printf("print the next class: ");
scanf("%s%s%*c", prof[c], grades[c]); /* scans in the class abbreviation and grade */
// inner for-loop for comparing the inputted class to make sure it is an accepted abbreviation
for(a = 0; a < ALL; a++){
i = strcmp(prof[c], allclasses[a]);
if(i == 0){checker++;
break;} /* if prof[c] == allclasses[a] */
}
// decreases int c by one to repeat the last loop cycle.
if(checker == 0){printf("The class is not recognized, please reenter the class and grade.\n"), c--;}
// if the last input is valid ask user to either continue or quit
else {printf("Class recognized and entered. type 'c' to proceed to enter the next class or 'q' to finish the profile.\n");
// do-while loop to make sure the user input is valid.
do{
inchar = scanchar(inchar);
if(inchar != 'q' && inchar != 'c')printf("Please enter either 'c' to continue entering the profile or 'q' to finish the profile: ");
}while(inchar != 'q' && inchar != 'c');
}
if(inchar == 'q'){counter = c;
c = MAX_PROF;}
}
fprintf(profilep, "%d", counter); /* prints the total number of classes in the profile first */
// for-loop for inputting all of the prof and grades array into the profile file.
for(i = 0; i <= counter; i++){
fprintf(profilep, " %s %s", prof[i], grades[i]);
}
}