C语言 press Y to Continue, N to Exit. 【防非法输入】

//Start of the Y/N
//可作为任何文件的模板,所需变量为 char exitInput; char BUF; 可以排除非法输入,诸如非法长度,输入回车等。读取用的是getchar,的确是麻烦很多,但是操作起来要比scanf思路清晰一点。
char exitInput;
char BUF;
//变量申明尽量放在函数开头
while(1){
while((BUF = getchar()) != ‘\n’){
while((BUF = getchar()) != ‘\n’ && BUF != EOF);
printf(“\npress Y to Continue, N to Exit: “);//非法长度
exitInput = getchar();
//添加这段的理由在于,检测到输入回车时,直接提示”press…”
while(exitInput == ‘\n’){
printf(“\npress Y to Continue, N to Exit: “);//输入回车
exitInput = getchar();
}
//printf(“2.【%c】\n”,exitInput);//调试
}
//如果不是YyNn就循环
if(exitInput != ‘N’ && exitInput != ‘n’ && exitInput != ‘Y’ && exitInput != ‘y’){
printf(“\npress Y to Continue, N to Exit: “);//非法字符
exitInput = getchar();
//添加这段的理由在于,检测到输入回车时,直接提示”press…”
while(exitInput == ‘\n’){
printf(“\npress Y to Continue, N to Exit: “);//输入回车
exitInput = getchar();
}
//printf(“4.【%c】\n”,exitInput);//调试
} else {
break;
}
//printf(“5.【%c】\n”,exitInput);//调试
}
if (exitInput == ‘N’ || exitInput == ‘n’){
break;
}
// End of the Y/N

受Wordpress编辑器限制,缩进不能显示,所以大家自己在线格式化一下

格式化地址:http://tool.oschina.net/codeformat/js