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

scanf-problem?

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;

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

      switch(action){
      case 'a' : printf("add");
                 break;
      case 'd' : printf("delete");
                 break;
      case 'q' : printf("quit");
                 exit(0);
      }
   }

}


0
sa9813
Asked:
sa9813
1 Solution
 
mattropeCommented:
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.
0
 
sylpheCommented:
Hello,

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 :

fflush(stdin);

after your scanf. It will clean your stdin (input) stream
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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