Printf () error after entering function in C

Hi, I had a problem while entering AddEmployee () function.

When I enter, I want him to print out "Name" to prompt the user to enter a name, but it displays the following:

::Add Employee::
First Name:Last Name:

So, instead of entering the first name, instead, when the user enters it, it is actually the last name that is scanned.

How to change the code so that it does not print

First Name:Last Name:

But rather

First Name: (whatever user enters)
Last Name: (whatever user enters)

Here is the code I wrote

#include <stdio.h>
#include <math.h>
#include <string.h>

struct Employee{

char FirstName[16];
char LastName[16];
char Address[21];
char ID[4];
char Duration[4];

};

void MainMenu();
void AddEmployee();


int main(int argc, char *argv[]) 
{
    MainMenu(); 
}


void MainMenu()
{   
    int main_menu = 0;

    printf("::Main Menu::\n");
    printf("1.) Add Employee:\n");
    scanf("%d", &main_menu);

    switch (main_menu) 
    {
        default:
        {
            printf("Invalid Choice!");
            break;
        }
        case(1):
        {
            AddEmployee();
            break;
        }
    }
}


void AddEmployee()
{   
    struct Employee employee;

    printf("::Add Employee::\n");
    printf("First Name:");
    fgets(employee.FirstName, 16, stdin);
    printf("Last Name:");
    fgets(employee.LastName, 16, stdin);

}
+4
source share
1 answer

Use getchar () to clear the input buffer by reading "\ n" to the left of the buffer.

void AddEmployee()
{   
    struct Employee employee;

    printf("::Add Employee::\n");
    printf("First Name:");
    getchar();
    fgets(employee.FirstName, 16, stdin);
    printf("Last Name:");
    fgets(employee.LastName, 16, stdin);

}

You can add getchar () even after scanf () in main (),

 printf("::Main Menu::\n");
    printf("1.) Add Employee:\n");
    scanf("%d", &main_menu);
    getchar();
    switch (main_menu) 
    {
        default:
        {
            printf("Invalid Choice!");
            break;
        }
        case(1):
        {
            AddEmployee();
            break;
        }

getchar() scanf() main(), \n, @Mike.

+3

Source: https://habr.com/ru/post/1533956/


All Articles