【发布时间】:2016-08-19 14:31:09
【问题描述】:
我刚刚从 stephen Kochan 的 programming in c 开始学习 c 中的 I/O 文件操作。在下面的一个练习题中
编写一个程序,一次在终端显示 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() 的行为。我正在尝试自己学习这些东西,我在谷歌上搜索了一个解释,但我一无所获。非常感谢您对此提供任何帮助和反馈。
【问题讨论】:
-
getchar返回一个int,而不是char,因为它必须返回EOF,所以请将again改为int -
但有些程序使用
getchar()来获取用户的下一个字符? -
@LưuVĩnhPhúc 我更改了它,但它的行为仍然相同