RafVasq
RafVasq

Reputation: 5

While / Switch Loop Implementation

When I run this code and I hit one of the switch's breaks (excluding case 'x') the first printf statement outputs twice. I'm not sure why this happens. Wondering if anybody can see it right from the code without needing the functions to actually run the program.

int main(void)
{
   int key;
   char command, word[STRINGMAX];
   struct data_node *first=NULL, *ptr, *new_node;

   while (command)
   {
      printf("Enter a list command (+-flx): ");
      scanf("%c", &command);
      switch(command)
      {
      case '+' :
         printf("'+' detected\n");
         printf("Enter key data: ");
         scanf("%d", &key);
         printf("What string to store?: ");
         scanf("%s", &word);
         first = ptr = insert(&first, key, word);
         break;

      case '-' :
         printf("'-' detected\n");
         printf("Enter key data: ");
         scanf("%d", &key);
         delete(&first, key);
         break;
      case 'f' :
         printf("'f' detected\n");
         printf("Enter a key data: ");
         scanf("%d", &key);
         find_node(first, key);
         break;
      case 'l' :
         printf("'l' detected\n");
         dump_list(first);
         break;
      case 'x' :
         printf("Goodbye.\n");
         exit(0);
      default :
         break;
      }
   }
   return (0);
}

Any help appreciated. Thanks.

Upvotes: 0

Views: 110

Answers (1)

user2852845
user2852845

Reputation:

Add a getchar() after reading a number and a string as scanf leaves the new line character in the input stream. It is preferable to use fgets().

Vivek

Upvotes: 1

Related Questions