Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is the %n format specifier working normal for all scanf() statements but storing one less in the first one?
    text
    copied!<p>The <code>%n</code> format specifier,when used in a <code>scanf()</code> is expected to store the count of the number of characters of the format string already processed by the function into an argument of type <code>int*</code>.According to the definition:</p> <p><code>The number of characters of the format string already processed is stored in the pointed location.</code></p> <p>But in my program,it works so in all but the first <code>scanf()</code>.In all <code>scanf()</code>s in my program,excluding the first one,it stores the count of the total number of characters entered from the console,including the newlines (<strong>Enter</strong> keys).But in the first <code>scanf()</code>, the count is <strong>one less than</strong> the total count of characters and newlines entered from the console.</p> <p>Please explain this anomaly as it's really frustrating that I can't detect this simple bug.</p> <pre><code>#include &lt;stdio.h&gt; int main () { int a,b,c,d,count; printf("First Trial\n"); scanf("%d%d%d%d%n",&amp;a,&amp;b,&amp;c,&amp;d,&amp;count); //OUTPUT ANOMALY HERE printf("count=%d\n",count); printf("Second Trial\n"); scanf("%d%n",&amp;a,&amp;count); printf("count=%d\n",count); printf("Third Trial\n"); scanf("%d%d%n",&amp;a,&amp;b,&amp;count); printf("count=%d\n",count); printf("Fourth Trial\n"); scanf("%d%n%d",&amp;a,&amp;count,&amp;b); printf("count=%d",count); } </code></pre> <p><strong>Sample Output</strong></p> <pre><code>First Trial 253 34 4 83 count=11 Second Trial 25 count=3 Third Trial 234 38 count=7 Fourth Trial 3534 35 count=5 </code></pre> <p><strong>Why in the first trial we get "11" instead of "12</strong>?That's my doubt.</p> <p><strong>CRUCIAL EDIT</strong></p> <p>Another finding.If for the first <code>scanf()</code>,instead of using <code>Enter</code> keys(newlines) to separate the numbers entered, if I use space,lots of whitespace,then all those whitespace are counted by <code>count</code> as well.For example I get <code>count=21</code>.It means the newlines,spaces,everything is being considered.But why it is <strong>one less</strong> for first trial?</p> <pre><code>First Trial 25 35 38 98 count=21 </code></pre>
 

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