Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your code prints line numbers at the end of a line, right before printing the <code>'\n'</code>, because of the way you have written the loop. Otherwise, your code should work.</p> <p>If you want your code to print the line numbers at the beginning, you can do something like (untested):</p> <pre><code>int line_num_printed = 0; /* indicating if we printed a line number */ int line = 1; while ((c = fgetc(fp)) != EOF) { if (!line_num_printed) { printf("LINE %d: ", line); line_num_printed = 1; } putchar(c); if (c == '\n'){ line++; line_num_printed = 0; } } </code></pre> <p>If there is something else that "doesn't work", you should post complete code and tell us what doesn't work.</p> <p><em>Edit</em>: The proper way to check a character for a newline is to test against <code>'\n'</code>. If the character came from a file, you should also make sure you open the file in text mode, i.e., without a <code>b</code> in the second argument to <code>fopen()</code>.</p> <p>Also, you want <code>c</code> to be of type <code>int</code>, not <code>char</code>. This is because in C, <code>EOF</code> is a small negative number, and if <code>char</code> is unsigned, comparing it against a negative number convert the value of <code>EOF</code> to a positive value (equal to <code>EOF + UCHAR_MAX + 1</code> most likely). Therefore, you should <em>not</em> change <code>c</code> to <code>char</code> type. If you do, the comparison <code>c != EOF</code> might be false even when <code>fgetc()</code> returns <code>EOF</code>.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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