When the program displays Do you have more students to input?
and you input yes
and then hit enter on console, then \n
will be stored in input stream.
You need to remove the \n
from the input stream. To do that simply call getchar()
function.
It will be good if you don't mix scanf
and fgets
. scanf
has lots of problems, better use fgets
.
Why does everyone say not to use scanf? What should I use instead?
Try this example:
#include <stdio.h>
#include <string.h>
int main (void)
{
int addstudents = 1;
char name[20];
char morestudents[4];
int students, c;
char *p;
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
//Remove `\n` from the name.
if ((p=strchr(name, '\n')) != NULL)
*p = '\0';
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf(" %s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
//Remove the \n from input stream
while ( (c = getchar()) != '\n' && c != EOF );
}
return 0;
}//end main