Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with scanf and fgets
    primarykey
    data
    text
    <p>This is for a homework assignment to sort some given strings. I'm prompting the user for the number of strings they'd like to sort with <code>scanf</code>, allocating an array based on that number, and then getting the strings themselves with <code>fgets</code>.</p> <p>Everything works fine if the number of strings is hardcoded, but the addition of <code>scanf</code> to let the user decide screws things up. Here's the code:</p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define LENGTH 20 // Maximum string length. int main(void) { int index, numStrings = 0; char **stringArray; printf("Input the number of strings that you'd like to sort: "); assert(scanf("%d", &amp;numStrings) == 1); stringArray = (char **)malloc(numStrings * sizeof(char *)); for (index = 0; index &lt; numStrings; index++) { stringArray[index] = (char *)malloc(LENGTH * sizeof(char)); assert(stringArray[index] != NULL); printf("Input string: "); assert(fgets(stringArray[index], LENGTH, stdin) != NULL); } // Sort strings, free allocated memory. return 0; } </code></pre> <p>And here's what the console looks like:</p> <pre> Input the number of strings that you'd like to sort: 3 Input string: Input string: foo Input string: bar </pre> <p>It skips over the first iteration of the loop, resulting in an empty string at the beginning of the array. My question is, why does it do that, and how can I fix it?</p> <hr> <p>Here's what the console looks with the format string <code>"%d\n"</code> passed to <code>scanf</code>:</p> <pre> Input the number of strings that you'd like to sort: 3 foo Input string: Input string: bar Input string: baz </pre> <p>So, I can input all of the strings, but the first prompt for a string is in the wrong place.</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.
 

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