This question already has answers here:
Simple C scanf does not work? [duplicate]
(5个答案)
4年前关闭。
我遇到以下代码的问题。如输出所示,在第一次调用
码:
输出:
(5个答案)
4年前关闭。
我遇到以下代码的问题。如输出所示,在第一次调用
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/