I've tried looking around and I can't seem to find where the error lies. I know it must have something to do with the way I used fgets but I can't figure out for the life of me what it is. I've read that mixing fgets and scanf can produce errors so I've even changed my second scanf to fgets and it still skips the rest of my inputs and only prints the first.
int addstudents = 1;
char name[20];
char morestudents[4];
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf("%s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
}
My inputs are Joe, yes, Bill, yes, John, no. All goes according to plan if I utilize scanf in lieu of the first fgets but I would like be able to use full names with spaces included. Where am I going wrong?
int c; while ((c = getchar()) != EOF && c != '\n') ;
where the semicolon for the loop body would be on a line on its own. This protects you if the user typesyes please
or just puts a space at the end of the input. In this case, it is crucial to useint c
instead ofchar c
. In the original code, you don't usec
(so my default compiler options would complain about a set but unused variable; I'd end up with(void)getchar();
if I used the code here) so it doesn't matter that you can't reliably distinguishEOF
from a valid character. – Middling