该程序读入一个文件,然后要求用户输入要显示的行数。显示行数后,将再次提示用户打印更多行或按回车键退出。
我很难通过捕获换行符和/或回车来退出。如果按下返回按钮,我的程序不会退出,但如果我输入 ascii 值(10 是换行的十进制),我的程序不会退出
我希望程序在按下 enter 时退出。
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *file = fopen(argv[1], "r");
int newLineCounter, currentChar, numOfLines;
printf("enter a number of lines of lines to be displayed\n");
scanf("%d", &numOfLines);
while ((currentChar = fgetc(file)) != EOF)
{
printf("%c", currentChar); //print character
if (currentChar == '\n') //check for newLine character
newLineCounter++;
if (numOfLines == newLineCounter)
{
printf("\nenter a number of lines to be displayed or just return to quit\n");
scanf("%d", &numOfLines);
newLineCounter = 0;
//supposed to exit if return is pressed
if (numOfLines == '\n') //????why does this only execute when the decimal value of newline is entered
return 0;
}
}
//printf("%d lines in the text file\n", newLineCounter);
fclose(file);
return 0;
}