C语言程序中gets()怎老是在执行时自动跳过不接受输入?

来源:百度知道 编辑:UC知道 时间:2024/06/06 07:37:33
在VC下调此程序时出现该问题...程序目的是输入三本书的信息.
#include<stdio.h>
#include<dos.h>
main()
{struct bnotes
{char bn[100];
char an[100];
int da_year;
int da_day;
int da_mon;
int sta;
}book[3];
int i;
system("cls");
for(i=0;i<3;i++)
{printf("\nInput the name of book%d:\n",i+1);
gets(book[i].bn);
printf("\nInput the author's name of book%d:\n",i+1);
gets(book[i].an);
printf("\nNow input the pressing date of the book:(yyyy-mm-dd)\n");
scanf("%d-%d-%d",&book[i].da_year,&book[i].da_mon,&book[i].da_day);
printf("\nFinally is the book borrowed?(Input 0 for no,others for yes)\n");
book[i].sta=getch();
}
for(i=0;i<3;i++)
{printf("\nThe book%d's name is %s,the author's name is %s,the pressing date is %d-%d-%d.\n",i+1,book[

这是一个字符串回车键重复读取问题,第一个字符串接收以后,可能在键盘的缓冲区里面还保存一个回车换行之类的键符。
解决办法是:
在新的读取之前,先输出一行键盘输入提示符。在提示符之前,在添加一句键盘缓冲区清除语句。清除键盘缓冲区也可以使用stdio.h中的标准函数完成,使用方法如下:
==================================
fflush(stdin) 或者: flushall()
对程序做如下修改:
==============================================
printf("\nInput the name of book%d:\n",i+1);
gets(book[i].bn);
printf("\nInput the author's name of book%d:\n",i+1);
gets(book[i].an);
改为:
============================
printf("\nInput the name of book%d:\n",i+1);
gets(book[i].bn);
flushall(); /* 用来去掉缓冲区中多余的回车换行符 */
printf("\nInput the author's name of book%d:\n",i+1);
gets(book[i].an);
=========================
一定可以解决的,试试吧。
该加分了吧?


fgets( book[i].bn, 100, stdin);
这种形式输入。
回车换行符就会含在字符串里,输入不会读乱。

读入的字符串长度等于 strlen(book[i].bn);
最后一个字符是 '\n'