[英]While loop repeating but don't know why
我正在編寫一個程序,該程序讀取文本文件的前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++;
后遞增,您的行始終為0。僅使用:
line++;
編輯 :好的,所以這不是問題。 我已經運行了您的程序,問題是當您在第一個scanf中輸入文件名時,請按Enter鍵,以便程序讀取它。 由於某種原因,該輸入(或換行符)在第二個scanf中被讀取為輸入。 只需在第一個scanf之后添加一個虛擬scanf即可吸收此換行符:
printf("Please enter the name of the file you wish to view\n");
scanf("%s", fname);
scanf("%c", &input); // dummy scanf
最重要的是,學習啟用所有警告和調試信息(在Linux上,使用gcc -Wall -g
),並學習如何使用調試器 (如Linux上的gdb
)。
沒有這兩者,您真的無法學習使用C進行編碼。
您應該使用stdin的fget而不是scanf,可以指定需要閱讀的角色數量,這樣更加安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.