[英]Printf() error after entering a function in C
Hi I am having an issue when I enter the AddEmployee() function. 嗨我输入AddEmployee()函数时遇到问题。
When I enter I want it to print out "First Name" to prompt the user to enter the first name, but it prints out the following: 当我输入时,我希望它打印出“名字”以提示用户输入名字,但它打印出以下内容:
::Add Employee::
First Name:Last Name:
So instead of the first name being entered, instead when the user inputs it is actually the last name that is being scanned in. 因此,不是输入第一个名称,而是在用户输入时,实际上是正在扫描的姓氏。
How do I change the code so that it won't print out 如何更改代码以使其无法打印出来
First Name:Last Name:
But rather 反而
First Name: (whatever user enters)
Last Name: (whatever user enters)
Here is the code I have written 这是我写的代码
#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);
}
Use getchar() to clear the input buffer by reading the '\\n' left in buffer. 使用getchar()通过读取缓冲区中的'\\ n'来清除输入缓冲区。
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 the getchar() even after the scanf() in main(), 你甚至可以在main()中的scanf()之后添加getchar(),
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;
}
and it is better to put getchar() right after the original scanf() in main() that resulted in left over \\n
in buffer, considering the comment by @Mike. 最好将getchar()放在main()中的原始scanf()之后,导致在缓冲区中留下
\\n
,考虑@Mike的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.