【发布时间】:2020-09-01 05:01:27
【问题描述】:
我是学习 C 语言的新手。 我已经从 C++ 转移并正在实现 while 并执行 while 循环
以下是我的代码中的一个 sn-p。这在 C++ 中运行良好,但在 C 中执行 while 循环后,一旦它首先执行 scanf 然后打印菜单,我无法弄清楚。请帮忙
#include <stdio.h>
int main() {
int ch;
char ans='y';
while(ans=='y'){
printf("\n1. Insert / Create linked list ");
printf("\n2. Insert at specific position ");
printf("\n3. Display ");
printf("\n4. Search element");
printf("\n5. Delete element");
printf("\n6. Exit");
printf("\nEnter choice \n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
break;
case 6 :
break;
}
printf("\nDo you want to continue ?\n");
scanf(" %c ",&ans);
printf("\n");
};
return 0;
}
【问题讨论】:
-
scanf()格式字符串中的尾随空格是可怕的——当输入应该是交互式的时更是如此。您必须在输入数字后键入一些不是空格的字符——因此用户必须在当前输入之前猜测/知道下一个输入应该是什么(scanf(" %d ", &ch);将终止。
标签: c while-loop do-loops