#include <stdio.h>
void clearKeyboard(void)
{
while (getchar() != '\n') ; // empty execution code block on purpose
}
int yes(void)
{
char a,b;
printf("<Please enter a character>: ");
scanf("%c%c", &a,&b);
while ((a !='Y' && a !='y' && a !='N' && a!='n') || (b!='\n'))
{
if (b!='\n') ungetc(b, stdin),scanf("%*[^\n]%c", &b);
a='n',b='\n';
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c%c", &a,&b);
}
if (a =='Y' || a=='y')
{
printf("Contact Management System: terminated\n");
return 1;
}
else
{
if (a =='N' || a=='n')
ContactManagerSystem();
return 0;
}
}
int menu(void)
{
int i;
printf("0. Exit\n\nSelect an option:> ");
scanf("%d", &i);
while (i<0 || i>6)
{
printf("*** OUT OF RANGE *** <Enter a number between 0 and 6>: ");
scanf("%d", &i);
}
return i;
}
void ContactManagerSystem(void)
{
int i=menu();
switch(i)
{
case 0 :
printf("Exit the program? (Y)es/(N)o: ");
yes();
}
}
int main(void)
{
ContactManagerSystem();
}
So my "yes" function is working fine on it's own but when I call it within
ContactManagerSystem()case 0由于某种原因而变得疯狂
“是”功能实际上是一个验证检查功能,我需要用户
输入“是”或“否”,如“ Y”,“ y” N”或“ n”
等待用户输入“ Y”,“ y”,“ N”或“ n”(是或否)。
如果用户回答是(“ Y”,“ y”),它将结束显示
以下消息:
联系人管理系统:已终止 否则,如果用户输入否(“ N”,“ n”),则应用程序继续执行
显示菜单。
最佳答案
我认为您需要重新考虑对&&
和||
的使用,并使用括号。这段代码还照顾到EOF和键入的单词(如“是”)。
#include <stdio.h>
int main(void)
{
char a, b;
printf("<Please enter a character>: ");
if (scanf("%c%c", &a, &b) == 2)
{
while ((a != 'Y' && a != 'y' && a != 'N' && a != 'n') || b != '\n')
{
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
if (b != '\n')
{
int c;
while ((c = getchar()) != EOF && c != '\n')
;
}
if (scanf("%c%c", &a, &b) != 2)
break;
}
if (a == 'Y' || a == 'y')
{
printf("Got yes!\n");
return 1;
}
else if (a == 'N' || a == 'n')
{
printf("Got no!\n");
return 0;
}
}
printf("Got EOF\n");
return 0;
}
如果
a
中的字母既不是'Y'
也不是'y'
也不是'N'
也不是'n'
,或者b
中的值不是换行符,则报告问题,请在所有换行符前添加所有杂散字符(或EOF),然后继续。通过打印报告状态以及退出状态。示例运行:
$ ./scan13; echo $?
<Please enter a character>: yes
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: no
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: pdq
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
Got yes!
1
$ scan13; echo $?
<Please enter a character>: n
Got no!
0
$ ./scan13; echo $?
<Please enter a character>: Got EOF
0
$
如以下注释中所述,
scanf()
的问题之一是确保错误行为符合预期。通常更容易使用fgets()
或POSIX getline()
将整行读入缓冲区,然后使用sscanf()
解析数据。关于c - 函数获取垃圾值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47804105/