このプログラムはファイルを読み込み、ユーザーに表示する行数を入力するように求めます。行数が表示された後、さらに行を印刷するか、または Return キーを押して終了するかをユーザーに再度求めるプロンプトが表示されます。
改行や改行をキャプチャして終了するのに苦労しています。戻るボタンを押してもプログラムは終了しませんが、ASCII 値を入力すると終了します (10 は改行の 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;
}