• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:


Hi, could somebody please explain to me
why, when this program is executed it prints
then scans the char, prints the string corresponding to that alternative, then prints
one time, then once more

how come it does not stop on the first time?

File: linked.c

   node * head;
   char action;

      printf(" >");
      scanf("%c", &action);

      case 'a' : printf("add");
      case 'd' : printf("delete");
      case 'q' : printf("quit");


1 Solution
When you type in something at the prompt and hit enter, two characters actually get stored in the STDIN buffer: the character you typed and a newline character.  The first character (the one you typed) gets stored in 'action' first, and then gets processed.  The next call to scanf finds something already in the buffer (a newline character) so it just uses that instead of waiting for something to be typed in.  Since you don't have a case for '\n' in your switch statement, your code doesn't do anything for the newline case except print out another prompt.

Hope that clears up your confusion.

If my memory is not too bad :

When you do scanf, you ask for a char, but in input you will obtain a char and ENTER (which is necessary to know that the user entered something )  ENTER is also a char and this second char will remain in the input buffer. So to overcome this you should add :


after your scanf. It will clean your stdin (input) stream
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Prepare for an Exciting Career in Cybersecurity

Help prevent cyber-threats and provide solutions to safeguard our global digital economy. Earn your MS in Cybersecurity. WGU’s MSCSIA degree program curriculum features two internationally recognized certifications from the EC-Council at no additional time or cost.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now