Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem with</p> <pre><code>while(scanf("%d%c",&amp;num,&amp;a) != 2 || a != '\n') { printf("Please enter an integer only : "); while(a != '\n') scanf("%c",&amp;a); } </code></pre> <p>is that if <code>a</code> happens to contain <code>'\n'</code> before the scan, and the scan fails, the inner <code>while</code> loop doesn't run at all. So</p> <ul> <li><p>if the scan failed trying to parse an <code>int</code> from the input stream because the input was e.g. <code>"ab c\n"</code>, the offending input remains in the input stream, the next <code>scanf</code> in the outer <code>while</code> loop control fails parsing an <code>int</code> again, <code>a</code> remains <code>'\n'</code>, repeat.</p></li> <li><p>if an input error occurred before reading a character from the stream into <code>a</code>, the <code>scanf</code> in the outer loop control fails because of a corrupted stream, repeat.</p></li> </ul> <p>In the other version,</p> <pre><code>while(scanf("%d%c",&amp;num,&amp;a) != 2 || a != '\n') { printf("Please enter an integer only : "); if(a == '\n') scanf("%c",&amp;a); else { while(a != '\n') scanf("%c",&amp;a); } } </code></pre> <p>you make at least some progress as long as there is input to be read from the stream, since whatever <code>a</code> contains, you read at least one character from the input stream before attempting the next parsing of an <code>int</code>. It will also result in an infinite loop if the input stream is corrupted/closed/ends prematurely, e.g. if you redirect stdin from an empty file. You can have that loop also output multiple <code>"Please enter an integer only : "</code> messages by giving input like `"a\nb\nc\nd\n".</p> <p>So you should check whether <code>scanf</code> encountered the end of the stream or some other read error before converting anything from the input, and abort in that case:</p> <pre><code>int reads; while(((reads = scanf("%d%c", &amp;num, &amp;a)) != 2 &amp;&amp; reads != EOF) || a != '\n') { printf("Please enter an integer only : "); // read at least one character until the next newline do { reads = scanf("%c", &amp;a); }while(reads != EOF &amp;&amp; a != '\n'); } </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