我在使用下面的代码时遇到了问题。如输出所示,调用 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/