【发布时间】:2011-12-06 11:37:33
【问题描述】:
我正在编写一个读取文本文件前 20 行的程序。当前 20 行被读取时,用户可以选择继续阅读接下来的 20 行或退出程序。然而发生在我身上的是它打印了 20 行,出现了用户提示,然后它自动打印了接下来的 20 行,而无需等待用户的输入。之后,它将打印用户提示,然后等待输入。我知道这是一个简单的问题,但我没有看到它!到目前为止,我已经根据对我的问题的答复稍微修改了代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char fname[20];
char c, input;
int line;
line = 0;
printf("Please enter the name of the file you wish to view\n");
scanf("%s", fname);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("The file did not open correctly");
exit(0);
}
else
{
printf("The file opened correctly\n");
}
while(c != EOF && input != 'q')
{
c = getc(fp);
printf("%c", c);
if (c == '\n')
{
line++;
while (line==20)
{
line = 0;
printf("Press return to view the next 20 lines or press q to quit:");
scanf("%c", &input);
if (input == 'q')
{
return 0;
}
else if (input == '\n')
{
line++;
}
}
}
}
return 0;
}
【问题讨论】:
-
我会避免像
line = line++这样的陈述。使用line = line + 1或line++,不要混合使用。看起来这不是您的问题,但将来可能会导致问题。 -
这里有很多或者说错的地方,乍一看:使用c和input unitialized,第一行=0然后行=1,fname只有20个字符,如果用户输入更长的名字怎么办? , word 没用,缩进没有意义,有 if 和 else if 但没有 else
-
c和input未初始化使用。 -
我已经初始化C并在开始时输入? Stijn,我知道目前在格式化等方面存在很多小错误,但我需要该程序才能工作。这是我现在最关心的问题!
-
@adohertyd:查看我的编辑以获取有关问题的更新。
标签: c loops while-loop