Fgets skips input

I've tried looking around and I can't seem to find where the error is. I know it must have something to do with how I used the fags, but I can't figure out how right I am. I read that mixing fgets and scanf can lead to errors, so I even changed my second scanf to fgets and it still skips the rest of my inputs and only prints the first ones.

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. Everything goes according to plan if I use scanf instead of the first fgets, but I would like to be able to use fully qualified names with spaces included. Where am I going wrong?

+3


source to share


1 answer


When the program displays Do you have more students to input?

and you type yes

and then hit enter on the console, then it \n

will be saved in the input stream.

You need to remove \n

from the input stream. To do this, just call the function getchar()

.

It's good if you don't mix scanf

and fgets

. scanf

has many problems, it is better to 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

      

+5


source







All Articles