执行期间未读取 fgets 函数[重复]

问题描述 投票:0回答:1

我是 C 初学者,在使用结构执行程序时遇到问题。 这是一个输入 3 名员工详细信息的程序...

printf("\nWelcome employee"); printf("\nEnter your name:");
fgets(e1.name, 15, stdin); printf("\nEnter your id:");
scanf("%d", &e1.id);
printf("\nEnter your DOB (dd/mm/yyyy):");
scanf("%d%d%d", &e1.d1.d, &e1.d1.m, &e1.d1.y);

这段代码重复 3 次,并进行一些更改以输入第二个和第三个员工的详细信息。

虽然程序在第一个员工的代码中运行良好,但它会跳过第二个和第三个员工的姓名。



Welcome employee

Enter your name: Abc

Enter your id: 1111

Enter your DOB (dd/mm/yyyy): 01/01/2000

Welcome employee

Enter your name:

Enter your id: 2222

Enter your DOB (dd/mm/yyyy): 02/02/2002

Welcome employee

Enter your name:

Enter your id: 1111

Enter your DOB (dd/mm/yyyy): 01/01/2000

我尝试使用 scanf 函数,但再次出现相同的结果,即名称部分被跳过。

c structure fgets
1个回答
0
投票

正如 Weather Vane 在您的问题中评论的那样,您不应该混合

fgets
scanf
。看来您对
scanf
更满意,但您不知道如何将输入截断为 15 个字符。我建议您使用类似的方法,仅使用
scanf
并截断为 14 个字符,以允许 15 个字符为
NULL
:

void get_employer_data(struct employee *e) 
{
   char c[15];       // Seems 15 is the size of your name buffer.
   int id, day, month, year;
   printf("\nWelcome employee"); 
   printf("\nEnter your name:");
   if (scanf(¨%.14s¨, &c) != 1) {   // If your buffer size is 15 gather one less so the last char is always the NULL char.
       // Example to handle error
       printf("Name error.");
       return;
   } 
   c[sizeof(c)/sizeof(c[0]) - 1] = 0;    // Just making sure is NULL terminated.
   // I dunno your Name constraints (except 15 chars length), but probably you should do some validation on the input

   printf("\nEnter your id:");
   if (scanf("%d", &id) != 1) {
       // Example to handle error
       printf("ID error.");
       return;
   } 
   // I dunno your ID constraints, but probably you should do some validation on the input

   printf("\nEnter your DOB (dd/mm/yyyy):");
   if (scanf("%d/%d/%d", &day &month, &year) != 3) {
       // Example to handle error
       printf("DOB error.");
       return;
   };
   // I would recommend you to do any data validation you consider you need, like is a valid day, month, year, etc.  

   // I prefer to assign once I have everything just in case.
   strncpy(&e->name, &c, 15);
   e->id = id;
   e->d1.d = day;
   e->d1.m = month;
   e->d1.y = year;
}

这将在函数内部获取员工数据。老实说,我认为问题可能与

fgets
scanf
的使用有关,但由于您没有显示整个代码,我无法确定。

© www.soinside.com 2019 - 2024. All rights reserved.