Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I really don't like using <code>scanf()</code>, prefer <code>fgets()</code>, then <code>sscanf()</code>.<br> Details below.<br> 2 key lines: </p> <pre><code>if (fgets(buf, sizeof(buf), stdin) == NULL) ... while (1 != sscanf(buf, " %8lu %c", &amp;AccontNummner, &amp;ch)); </code></pre> <p>Solution</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // Get 8 digit account number. Returns -1 on I/O error or EOF // Parsing error just tries again. long Get8DigitAccountNumber(void) { const char *prompt = "Enter 8 digit account number: "; unsigned long AccontNummner; char ch; // Extra text char buf[1024]; do { // or while (1) ch = '\0'; printf(prompt); fflush(stdout); // Appears to be needed on some systems. prompt = "Error, try again: "; // Used on re-try if (fgets(buf, sizeof(buf), stdin) == NULL) { return -1; // handle I/O error } // If not _exactly_ one 1-8 digit field parsed, then try again. // Leading and trailing whitespaces are OK } while (1 != sscanf(buf, " %8lu %c", &amp;AccontNummner, &amp;ch)); return (long) AccontNummner; } int main() { long AccontNummner; while ((AccontNummner = Get8DigitAccountNumber()) &gt;= 0) { printf("# %lu\n", AccontNummner); } return 0; } </code></pre> <p>If you want to read <em>exactly</em> 8 digits ...</p> <pre><code> int n1 = 0; int n2 = 0; } while ((1 != sscanf(buf, " %n%8lu%n %c", &amp;n1, &amp;AccontNummner, &amp;n2, &amp;ch) || ((n2 - n1) != 8)); </code></pre> <hr> <p>Acceptable format: [optional whitespaces][1-8 digits][optional whitespaces][nothing more]<br> <code>sscanf()</code> format: <code>" %8lu %c"</code>.<br> Use <code>%u</code> instead of <code>%d</code> to not allow <code>'-'</code>.<br> Explicitly allow optional leading and trailing spaces.<br> The <code>%c</code> catches any non-white char after the 8-digit number.<br> Scanning anything via <code>%c</code> causes <code>sscanf()</code> to return 2. </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. 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