Reputation: 141
What would I have to modify so the original statements(the two printfs) prompting the user for their choice keeps repeating after the user made their selection? For example:
while(1) {
printf("What would you like to do next? \n");
printf("\tC to create more\n\tD to display\n\tI to insert at beginning\n\tN to exit\n");
scanf(" %c", &response);
switch(response) {
case 'C' : create(); scanf(" %c", &response);
case 'D' : display(); scanf(" %c", &response);
case 'I' : insert_at_beg(); scanf(" %c", &response);
case 'N': exit(0);
default : printf("Invaild choice. Bye\n"); exit(0);
}
}
I know my logic is all over the place in some places.
Upvotes: 0
Views: 452
Reputation: 1836
You have two problems here.
One is :
You did not use break statement between the case. In your case there is no need to put scanf statement after each case, just replace all scanf in switch with break. t is mandatory to use break if there are more then 1 case. Because switch is not an alternative of if ... else statements.
Second is :
It goes into an infinite loop because scanf() will not consumed the input token if match fails. scanf() will try to match the same input again and again. you need to flush the stdin. (fflushing an input stream invokes undefined behaviour. It is a strict don't. ).
if (!scanf(" %c", &response)) fflush(stdin);
Otherwise try this
if (scanf(" %c", &response) == 0) { break; }
Upvotes: 1