Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use <code>fgets()</code>, <code>sscanf()</code> and additional code to parse. </p> <p>This parsing would be more robust if the separator (a space) was not allowed in a field. The potential space or spaces within <code>.name</code> convoluted the parsing. Recommend comma separated fields. Further the <code>int n2[10]</code> field is unusual. Why not <code>unsigned long long n2</code>?</p> <p>Be sure to check result of <code>fgets()</code>, <code>sscanf()</code>.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; typedef struct ex { int n1; char name[14]; int n2[10]; } ex; int ReadEx(ex *dest) { char buf[20 + 1 + 14 - 1 + 1 + 10 + 2]; // Or use something big like buf[100] if (fgets(buf, sizeof buf, stdin) == NULL ) { return -1; // EOF or I/O Error } char name[14 + 1]; // temp place for name and final space separator int p1, p2; // Offset for beginning and end of n2 array unsigned long long ull; // Dummy to save n2 array if (3 != sscanf(buf, "%d %14[A-Za-z ]%n%llu%n", &amp;dest-&gt;n1, name, &amp;p1, &amp;ull, &amp;p2)) { return 1; // format error } // strlen(name) cannot have the value of 0 here as sscanf() is 3 size_t SpaceIndex = strlen(name) - 1; if ((name[SpaceIndex] != ' ') || ((p2 - p1) != 10)) { return 1; // format error, space expected at end of name and 10 digits } // name cannot contain only spaces due to the space before %14 while (name[SpaceIndex] == ' ') { name[SpaceIndex--] = '\0'; } strcpy(dest-&gt;name, name); int i; for (i = 0; i &lt; 10; i++) { dest-&gt;n2[i] = buf[p1 + i] - '0'; } return 0; // One could use the below approach but it is not so extensible. // if (12 != sscanf(buf, "%d %14[A-Za-z ]%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d %c", // &amp;dest-&gt;n1, name, &amp;dest-&gt;n2[0], &amp;dest-&gt;n2[1], ... &amp;dest-&gt;n2[9], &amp;dummychar)) { } </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