Scanf只能交替工作

时间:2015-12-10 08:50:45

标签: c gcc

我遇到以下代码的问题。正如输出所示,在第一次调用scanf("%c", &choice);之后,scanf似乎停止了下一次迭代,并且default情况正在执行。然而,之后scanf再次正常工作,然后下次不能工作。这个循环还在继续。我无法理解这个问题。是什么原因?

代码:

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;
}

输出:

        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
.
.
.

1 个答案:

答案 0 :(得分:2)

在阅读选项时,您需要跳过前导空格(上一个换行符)。只需在格式字符串中添加%c之前的空格:

scanf(" %c", &choice);