Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy scanf("%c\n") have a delay in stdin
    primarykey
    data
    text
    <p>Well , I know there are lots of question about <code>scanf</code>, but I still want to ask. I hope someone can explain the rules or principle for this issue:</p> <p>code first:</p> <pre><code> #include &lt;stdio.h&gt; int main() { int c = 'W'; while(c != 'F'){ scanf("%c",&amp;c); printf("c is : %c\n",c); } return 0; } </code></pre> <p>And here is the output:</p> <pre><code>E c is : E c is : &lt;--newline G c is : G c is : &lt;---newline again W c is : W c is : &lt;---newline F c is : F </code></pre> <p>Well, I still can understand by now, for the newline I input stay in buffer and assignment c every time after alphabet a press.So , I try code2:</p> <pre><code> #include &lt;stdio.h&gt; int main() { int c = 'W'; while(c != 'F'){ scanf("%c\n",&amp;c); //&lt;-- the only modified place. printf("c is : %c\n",c); } return 0; } </code></pre> <p>Then I get this screen:</p> <pre><code>E G &lt;---why the input and has one step before the output? c is : E W c is : G S c is : W C c is : S F c is : C R &lt;---R was left in stdin, turn to a garbage, I didn't hope this. c is : F </code></pre> <p>I also have try to flush the <code>stdin</code> and <code>stdout</code>, still no use.</p> <p><em>Note</em> : I know if use <code>scanf("%c",c);</code>and another <code>scanf("%c",&amp;d);</code> behind to deal with <code>'\n'</code> can fixed this, I just confuesed ,<strong>I hope to understand why the code2's issue happened.</strong></p> <p>I have check the answer before but I am not a really careful man , if this answer is really duplicate ,all downvote can be understand. :)</p> <p>Thanks in advance.</p>
    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.
 

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