我有一个让我困惑的小程序。我正在尝试使用循环来获取用户的输入。如果输入错误,则再次重复,如果正确,则退出。
代码片段是:
void main()
{
char user_status; // Checks User Status q = Quiz Master and p = Participant
int valid_status = '0'; // Checks If User Status Is Valid Or Not. Used In Some Loops. 0 = Invalid, 1 = Invalid.
printf("Welcome to General Knowledge Quiz Management System.\nThis application has been designed to help you conduct a quiz or test your GK.");
do
{
user_status = '0';
printf("\n\nPlease enter your role.\nQuiz Master = \'q\'\nParticipant = \'p\'\n");
scanf("%c", &user_status);
if (user_status == 'q'|| user_status == 'Q')
{
printf("Initializing Quiz Master Segment\n\n________________________________\n");
initiate_qm();
valid_status = '1';
}
else if (user_status == 'p' || user_status == 'P')
{
printf("Initializing Participant Segment");
initiate_pa();
valid_status = '1';
}
}
while (valid_status != '1')
printf("\nProgram Will Exit Now. Press Any Key To Return To Windows.");
getch();
}
因为你给了 scanf 三个字符来处理。它在第一次调用 scanf 获取“a”时删除第一个第一个字符,但在标准输入缓冲区中仍然保留“bc”。
在再次寻找输入之前,您需要检查缓冲区中是否有剩余的内容。我会避免刷新标准输入缓冲区,因为它是未定义的行为。 (http://www.gidnetwork.com/b-57.html)
您可以读取剩余的字符并丢弃它们
do{
scanf("%c", &user_status);
}while(user_status!='\n'); //This discards all characters until you get to a newline
当你读完你想要的角色后。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)