Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You seem to have a faulty understanding of scanf's format string. %d explicitly means "I'm looking for an integer." This is why you only get the ASCII digit representation of the new line character.</p> <p>If you want to capture a new line as a character, your scanf needs to be %c. Then you can write a simple function that will convert the character representation of the integer into the actual integer. However %c will also only read a single character, so what you really want to use is %s to read a series of characters (also known as a String) that will be placed in a character pointer variable or character array if you know the maximum number of digits you're willing to accept. There are few differences between a character array and a String. Specifically a String is a character array that is null terminated (the last element of the string is the null character, \0).</p> <p>Long answer short, use a character pointer and change your scanf format string to be %s. Then check to see if the first character is \n. If it is not, convert the string to an integer and use that value to read your lines.</p> <p>Below is your code altered slightly to reflect this solution.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; 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", &amp;numOfLines); while ((currentChar = fgetc(file)) != EOF) { printf("%c", currentChar); //print character if (currentChar == '\n') //check for newLine character newLineCounter++; if (numOfLines == newLineCounter) { char* input; printf("\nenter a number of lines to be displayed or just return to quit\n"); scanf("%s", &amp;input); if( input[0] == '\n' || input[0] == '\0' ){ return 0; } else { numOfLines = atoi( input ); } 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; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload