-1

I am facing a problem with the code below. As the output shows, after calling scanf("%c", &choice); the first time, scanf seems to stop working for next iteration and the default case is executing. However after that scanf works fine one more time and then doesn't work the next time. This cycle goes on. I am not able to understand the issue. What is the reason?

Code:

int main()
{
    char choice;
    int value;
    node *root = NULL;
    printf("\tA. add node\n\tB. inorder\n\tC. pre order\n");
    printf("\tD. delete node\n\tE. post order\n\tF. Ascending\n");
    printf("\tD. Descending\n");
    do {
        printf("Enter your choice\n");
        scanf("%c", &choice);
        switch (choice) {
            case 'A':
                printf("Enter value\n");
                scanf("%d", &value);
                addnode(&root, value);
                break;

            case 'B':
                inorder(root);
                break;

            case 'C':
                preorder(root);
                break;

            case 'D':
                printf("Enter value\n");
                scanf("%d", &value);
                deletenode(&root, value);
                break;

            case 'E':
                postorder(root);
                break;

            case 'F':
                ascending(root);
                break;

            case 'G':
                descending(root);
                break;

            case 'X':
                printf("Good Bye\n");
                break;

            default:
                printf("Enter proper choice\n");
                break;
        }
    } while(choice != 'X');
    return 0;
}

Output:

        A. add node
        B. inorder
        C. pre order
        D. delete node
        E. post order
        F. Ascending
        D. Descending
Enter your choice
A
Enter value
2
Enter your choice
Enter proper choice
Enter your choice
A
Enter value
4
Enter your choice
Enter proper choice
Enter your choice
D
Enter value
4
Enter your choice
Enter proper choice
Enter your choice
.
.
.
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
Jagdish
  • 1,848
  • 3
  • 22
  • 33

1 Answers1

2

You need to skip leading whitespace (previous newline) when reading the choice. Just add a space before %c in the format string:

scanf(" %c", &choice);
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60