首页 > 解决方案 > C-fgets 或 scanf

问题描述

for(i=0;i<requestnum;i++)
{
   bookcount++;
   printf("\n\nEnter Booking Request #%d", bookcount);
   printf("\nLast Name:");
   fgets(OneClient[i].LastName,100,stdin);
   if(!strcmp(OneClient[i].LastName, "\n"))
{
    printf("Processed %d successful requests out of %d submitted 
    requests.\nGenerating management report.\nThank you for using the hotel 
    reservation system.\nBye!",succescount, bookcount);
    exit(1);
}
printf("First Name:");
scanf(" %s", OneClient[i].FirstName);
}

fgets 在第一个循环中完成它的工作,但是当第二个循环发生时,它会扫描并存储一个空白字符并且不等待用户输入,我使用 fgets 因为我需要在用户输入空白时终止循环. 请帮助解决我的问题?

标签: c

解决方案


fgets正在阅读流中\n遗漏scanf的内容。

只需替换scanffgets.

for(i=0;i<requestnum;i++)
{
   bookcount++;
   printf("\n\nEnter Booking Request #%d", bookcount);
   printf("\nLast Name:");
   fgets(OneClient[i].LastName,100,stdin);
    ......
    .....
   printf("First Name:");

   /*Assumed FirstName is not pointer*/
   fgets(OneClient[i].FirstName, sizeof(OneClient[i].FirstName), stdin);
}

推荐阅读