gpt4 book ai didi

c - 函数获取垃圾值

转载 作者:行者123 更新时间:2023-11-30 18:35:09 26 4
gpt4 key购买 nike

 #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 由于某种原因它变得疯狂 “yes”功能实际上是一个验证检查功能我需要用户 输入“yes”或“no”,如 'Y''y''N' 或 'n' 等待用户输入“Y”、“y”、“N”或“n”(表示"is"或“否”)。 如果用户回答"is"(“Y”,“y”),则会结束程序,显示 以下消息:

Contact Management System: terminated< (followed by a newline) Otherwise, if the user entered No (“N”,”n”), the application continues to display the menu.

最佳答案

我认为您需要重新考虑对 &&|| 的使用,并使用括号。此代码还负责处理 EOF 和键入的单词(如“yes”)。

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com