Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You probably used <code>scanf</code> to read <code>choice</code> before calling <code>fgets</code> to read the name. <code>scanf</code> may have left a newline in <code>stdin</code> which your code mistakes for an empty name input. If that is indeed the case, try not to use <code>scanf</code> (use <code>fgets</code> to retrieve <code>choice</code> and use <code>atoi</code> to conver to <code>int</code> or <code>strcmp</code> to compare against "1\n" etc.). The code should otherwise work, with the below modifications to account for the fact that <code>fgets</code> also reads the terminating newline into the buffer (which you probably want stripped):</p> <pre><code> #define MY_LENOF(x) (sizeof(x)/sizeof((x)[0])) char choice[3] = { 0 }; /* example of how to initialize to all NULs */ if (!fgets(choice, MY_LENOF(choice), stdin)) { fprintf(stderr, "Premature end of input\n"); exit(1); } if (strcmp(choice, "1\n") == 0) { /*Name*/ printf("\nEnter the name:"); if (!fgets(name, MY_LENOF(name), stdin)) { /* if fgets fails it leaves name unchanged, so we reset it to "" */ name[0] = '\0'; } /* good practice to use srtnlen in order not to overrun fixed buffer */ /* not necessarily a problem with fgets which guarantees the trailing NUL */ size_t nameLength = strnlen(name, MY_LENOF(name)); assert(name[nameLength] == '\0'); if (nameLength - 1 &gt; 0 &amp;&amp; name[nameLength - 1] == '\n') { /* strip trailing newline */ name[--nameLength] = '\0'; } else if (nameLength &gt;= MY_LENOF(name) - 1) { fprintf(stderr, "Name is too long\n"); exit(1); } else { fprintf(stderr, "Premature end of input\n"); exit(1); } record.nameLength = nameLength; record.name = malloc(sizeof(char)*(record.nameLength + 1)); strcpy(record.name, name); </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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