Note that there are some explanatory texts on larger screens.

plurals
  1. POOptional parameters in fscanf [C]
    text
    copied!<p>Hello I am struggling with creating my menu for my linked list. I am told to use fscanf to take in input, but I have an argument that the user may not always enter, specifically a number to add to the linked list. The way I have fscanf set up is it reads a char, a number, and then another char (the [enter] key). E.g. the user enters "a 20[enter]" to add the number 20 to the linked list. However, if the user enters "d[enter]", then the num field is invalid because the user entered a char! Note I <strong>cannot</strong> use fgets(). </p> <p>Do I need another fscanf field? Here's my menu code below:</p> <pre><code>int main(void) { struct node* head = NULL; int num, ret; char select = 'n'; char c; while (select != 'e') { printf("Enter:\na(dd) (x) = add a new node with value x to the list at the front of the list\n"); printf("d(el) = delete the first node of list\n"); printf("l(ength) = print the number of nodes in the list\n"); printf("p(rint) = print the complete list\n"); printf("z(ero) = delete the entire list\n"); printf("e(xit) = quit the program\n"); ret = (fscanf(stdin, "%c %d%c", &amp;select, &amp;num, &amp;c)); if (ret == 3 &amp;&amp; select == 'a' &amp;&amp; c == '\n') Add(&amp;head, num); else if (ret == 2 &amp;&amp; select == 'd') Delete(&amp;head); else if (ret == 2 &amp;&amp; select == 'l') Length(head); else if (ret == 2 &amp;&amp; select == 'p') PrintList(head); else if (ret == 2 &amp;&amp; select == 'z' ) ZeroList(&amp;head); else printf("invalid\n"); } return EXIT_SUCCESS; } </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