Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Normally you read files in C using <code>fgets</code>. You can also use <code>scanf("%[^\n]")</code>, but quite a few people reading the code are likely to find that confusing and foreign.</p> <p>Edit: on the other hand, if you really do just want to count lines, a slightly modified version of the <code>scanf</code> approach can work quite nicely:</p> <pre><code>while (EOF != (scanf("%*[^\n]"), scanf("%*c"))) ++lines; </code></pre> <p>The advantage of this is that with the '*' in each conversion, <code>scanf</code> reads and matches the input, but does nothing with the result. That means we don't have to waste memory on a large buffer to hold the content of a line that we don't care about (and still take a chance of getting a line that's even larger than that, so our count ends up wrong unless we got to even <em>more</em> work to figure out whether the input we read ended with a newline).</p> <p>Unfortunately, we do have to break up the <code>scanf</code> into two pieces like this. <code>scanf</code> stops scanning when a conversion fails, and if the input contains a blank line (two consecutive newlines) we expect the first conversion to fail. Even if that fails, however, we want the second conversion to happen, to read the next newline and move on to the next line. Therefore, we attempt the first conversion to "eat" the content of the line, and then do the <code>%c</code> conversion to read the newline (the part we really care about). We continue doing both until the second call to <code>scanf</code> returns <code>EOF</code> (which will normally be at the end of the file, though it can also happen in case of something like a read error).</p> <p>Edit2: Of course, there is another possibility that's (at least arguably) simpler and easier to understand:</p> <pre><code>int ch; while (EOF != (ch=getchar())) if (ch=='\n') ++lines; </code></pre> <p>The only part of this that some people find counterintuitive is that <code>ch</code> <em>must</em> be defined as an <code>int</code>, not a <code>char</code> for the code to work correctly.</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.
    3. VO
      singulars
      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