I刚刚开始学习c中的I/O文件操作,从stephen 在c中的编程开始学习。在其中一个练习问题中,如下所示
编写一个程序,在终端上一次显示20行文件的内容。在每20行的末尾,让程序等待从终端输入一个字符。如果字符是字母q,程序应该停止文件的显示;任何其他字符都应该导致显示文件中接下来的20行。
#include<stdio.h>
int main(void)
{
int count=0,c;
FILE *fname;
char name[64];
char again='a';
printf("enter the name of file to be read : ");
scanf("%s",name);
if((fname=fopen(name,"r"))==NULL){
printf("file %s cannot be opened for reading \n",name);
return 1;
}
while(again!='q'){
count=0;
while((c=getc(fname))!=EOF)
{
if(c!='\n')
{
putchar(c);
}
else{
putchar('\n');
count++;
printf("count = %i\n",count); //debug statement
}
if(count>19)
break;
}
again=getchar();
printf("again = %c\n",again); //debug statement
}
fclose(fname);
printf("\n");
return 0;
}在上面的程序中,当我最初查看输出时,程序显示了40个数字,没有在20个数字下休息,所以我在上面包含了一些调试语句,以了解我出了什么问题,得到的输出是:
count = 1
2
count = 2
3
count = 3
4
count = 4
5
count = 5
6
count = 6
7
count = 7
8
count = 8
9
count = 9
10
count = 10
11
count = 11
12
count = 12
13
count = 13
14
count = 14
15
count = 15
16
count = 16
17
count = 17
18
count = 18
19
count = 19
20
count = 20
again = //it skipped the loop the first time
21
count = 1
22
count = 2
23
count = 3
24
count = 4
25
count = 5
26
count = 6
27
count = 7
28
count = 8
29
count = 9
30
count = 10
31
count = 11
32
count = 12
33
count = 13
34
count = 14
35
count = 15
36
count = 16
37
count = 17
38
count = 18
39
count = 19
40
count = 20
q
again = **need to input here**因此,getchar()第一次没有提示输入。因此,我替换了getchar()所在的部分:
scanf(" %c",&again);一切如期而至。这个程序在20行之后第一次提示输入。我还留了一些空白,这样scanf就会忽略它。这么长时间后,我想我还没有完全理解getchar()的行为。我正试着自己学习这些东西,我在谷歌上搜索了一个解释,但我发现自己是空的。任何有关这方面的帮助和反馈将是非常感谢的。
发布于 2016-04-26 04:42:50
修正代码。我还没有删除调试语句。
#include<stdio.h>
int main(void)
{
int count=0,c;
FILE *fname;
char name[64];
char again='a';
printf("enter the name of file to be read : ");
scanf("%s",name);
getchar();
if((fname=fopen(name,"r"))==NULL){
printf("file %s cannot be opened for reading \n",name);
return 1;
}
while(again!='q'){
count=0;
while((c=getc(fname))!=EOF)
{
if(c!='\n')
{
putchar(c);
}
else{
putchar('\n');
count++;
printf("count = %i\n",count); //debug statement
}
if(count>19)
break;
}
again=getchar();
printf("again = %c\n",again); //debug statement
}
fclose(fname);
printf("\n");
return 0;
}我所做的是,在scanf()之后添加了一个scanf()。若要清除缓冲区中scanf()留下的scanf(),请执行以下操作。
https://stackoverflow.com/questions/36853463
复制相似问题