c - scanf仅交替工作

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

最佳答案

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

scanf(" %c", &choice);

关于c - scanf仅交替工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197320/

相关文章:

c++ - 没有匹配的函数来调用

c - 错误代码+GCC 5.4优化导致死循环

c++ - 对齐外部常量 (gcc)

c - gcc:从硬件寄存器读取时 '-fno-strict-aliasing' 的奇怪行为

c - 为什么使用 elm chan fatfs f_chdir 更改目录不会影响目录结构?

c - 在 C 编程中反转前 n 个数字的数组

c - 在C中实现字符串复制函数

c - 为什么ld无法从/etc/ld.so.conf中的路径找到库?

c - C 中不兼容的指针类型

c - 分配 - 指针到指针