这最初来自另一个程序,但是这个片段不会按照我需要的方式工作,我想其他人可能也遇到了麻烦。还要注意的是,在接受用户输入后,它会在 while 循环中使用。
printf("would you like to check another time?(y/n)?");
fflush(stdin);
scanf("% c", &yesno);
while(yesno != 'y' && yesno != 'n')
{
printf("That was not a valid entry, please re entery your choice.");
fflush(stdin);
scanf("% c", &yesno);
}/*End of verification loop*/
我想让用户输入一个字符,在验证它是 y 还是 n 之后,让它进入一个 while 循环,如果字符是 y 它将继续程序,否则它将结束程序。
最佳答案
printf("would you like to check another time?(y/n)?\n");
fflush(stdin);
scanf("%c", &yesno);
while(yesno != 'n' && yesno != 'y')
{
printf("That was not a valid entry, please re-enter your choice.\n");
fflush(stdin);
scanf("%c", &yesno);
}
if (yesno == 'n') return 0; // program terminated here
// else it is automatically 'y' so your program continues here ...
额外的
我刚刚注意到另一个影响您的代码段的关键故障(我想下一行代码也会)
scanf("% c", &yesno); // will not read input
scanf("%c", &yesno); // will read input, there is no space between % and c, it is %c not % c
关于c - 验证循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801415/