Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is the correct way to do it, it is a little longer than the simplest way but it doesn't suffer from undefined behavior if the value read is out of range, works properly if the first character is not a dot, etc. You didn't specify whether the numbers could be negative so I used a signed type but only allow positive values, you can easily change this by allowing the negative sign at the top of the inner while loop. This version allows any non-digit characters to delimit integers, if you only want dots to be allowed you can modify the inner loop to skip only dots and then check for a digit.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; #include &lt;errno.h&gt; #define ARRAY_SIZE 10 size_t store_numbers (const char *s, long *array, size_t elems) { /* Scan string s, returning the number of integers found, delimited by * non-digit characters. If array is not null, store the first elems * numbers into the provided array */ long value; char *endptr; size_t index = 0; while (*s) { /* Skip any non-digits, add '-' to support negative numbers */ while (!isdigit(*s) &amp;&amp; *s != '\0') s++; /* Try to read a number with strtol, set errno to 0 first as * we need it to detect a range error. */ errno = 0; value = strtol(s, &amp;endptr, 10); if (s == endptr) break; /* Conversion failed, end of input */ if (errno != 0) { /* Error handling for out of range values here */ } /* Store value if array is not null and index is within array bounds */ if (array &amp;&amp; index &lt; elems) array[index] = value; index++; /* Update s to point to the first character not processed by strtol */ s = endptr; } /* Return the number of numbers found which may be more than were stored */ return index; } void print_numbers (const long *a, size_t elems) { size_t idx; for (idx = 0; idx &lt; elems; idx++) printf("%ld\n", a[idx]); return; } int main (void) { size_t found, stored; long numbers[ARRAY_SIZE]; found = store_numbers("..1....10..20....30...40....50...80...", numbers, ARRAY_SIZE); if (found &gt; ARRAY_SIZE) stored = ARRAY_SIZE; else stored = found; printf("Found %zu numbers, stored %zu numbers:\n", found, stored); print_numbers(numbers, stored); return 0; } </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