scanf()在文件处理中不起作用?
我的代码是scanf()在文件处理中不起作用?,c,file,struct,scanf,C,File,Struct,Scanf,我的代码是 struct bat { char name[20]; int runs; }b1; void main() { char ch='y'; FILE *p; p=fopen("details.dat","wb"); if(p==NULL) { printf("unable"); exit(0); } el
struct bat
{
char name[20];
int runs;
}b1;
void main()
{
char ch='y';
FILE *p;
p=fopen("details.dat","wb");
if(p==NULL)
{
printf("unable");
exit(0);
}
else
{
while ( ch == 'y' )
{
printf("enter details");
scanf("%s%d",b1.name,&b1.runs);
fwrite(&b1,sizeof(b1),1,p);
printf("do you want to eneter more");
scanf("%c",&ch);//it is not working
}
}
return 0;
}
如果我使用getche()来代替scanf,那么代码可以完美地工作,并具有所需的输出。
但是为什么它不使用scanf()?scanf()以一种特殊的方式工作。使用它扫描字符时,用户输入的所有击键都存储在缓冲区中,并在变量中重复覆盖。
因此,如果输入“y”,然后按“回车键”,scanf()将首先在字符变量ch中存储“y”的ascii值,然后立即用“回车键”的ascii值覆盖它
因此,您的条件ch=='y'失败,因为ch不再持有'y',而是持有'Enter key',导致代码失败
getch()或getche()非常适合在您的案例中使用。因为它只接受来自键盘的一次击键,并将其存储到指定的变量中,而无需按Enter键。这两个函数之间的唯一区别是getche()会回显屏幕上的字符,但getch()不会
希望这有帮助 您声明了
charc='y'
,但代码的其余部分引用了ch
。这是打字错误吗?是否在其他地方定义了ch
,且未初始化为y
?%c
更改为%c