Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.</p> </blockquote> <p>The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just <code>'\n'</code> for newlines.</p> <p>If you typed a character and pressed enter, then that input character would be read by line 1, and then <code>'\n'</code> would be read by line 2. See <a href="http://c-faq.com/stdio/scanfc.html" rel="noreferrer">I'm using <code>scanf %c</code> to read a Y/N response, but later input gets skipped.</a> from the comp.lang.c FAQ.</p> <p>As for the proposed solutions, see (again from the comp.lang.c FAQ):</p> <ul> <li><a href="http://c-faq.com/stdio/stdinflush.html" rel="noreferrer">How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will <code>fflush(stdin)</code> work? </a></li> <li><a href="http://c-faq.com/stdio/stdinflush2.html" rel="noreferrer">If <code>fflush</code> won't work, what can I use to flush input?</a></li> </ul> <p>which basically state that the only portable approach is to do:</p> <pre><code>while ((c = getchar()) != '\n' &amp;&amp; c != EOF) { } </code></pre> <p>Your <code>getchar() != '\n'</code> loop works because once you call <code>getchar()</code>, the returned character already has been removed from the input stream.</p> <p>Also, I feel obligated to discourage you from using <code>scanf</code> entirely: <a href="http://c-faq.com/stdio/scanfprobs.html" rel="noreferrer">Why does everyone say not to use <code>scanf</code>? What should I use instead?</a> </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.
    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