This program reads in a file and then asks the user to enter a number of lines to be displayed. After the number of lines have been displayed, the user is prompted again for either more lines to be printed or to quit by pressing return.
I'm having difficulty quitting by capturing the newline and/or carriage returns. My program does't quit if the return button is pressed but does if I put the ascii value (10 is decimal for newline)
I want the program to quit when enter is pressed.
#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;
}
Instead of using scanf, you can use:
That way you can detect empty lines.
To parse the integer from a non-empty line, you can use:
So your program should be something like: