c - 验证循环

标签 c loops scanf

这最初来自另一个程序,但是这个片段不会按照我需要的方式工作,我想其他人可能也遇到了麻烦。还要注意的是,在接受用户输入后,它会在 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/

相关文章:

c - 程序输出问题

c - 如何在 C 程序中将一个长整数与不同的数字相乘?

C 编译器可以在结构中的第一个元素之前添加填充吗?

c# - 为什么这个循环这么慢?

azure - 从所有表的 azure databricks 数据库列获取值

c - 使用 sscanf 读取字符串缓冲区

c - getenv 不适用于 COLUMNS 和 LINES

c - 为什么这个 C 程序在小数值后打印 %?

c - 在这个程序中,语句 "i is 1"应该在我输入值 2 之前而不是之后打印。?

c - fscanf() 的哪个正则表达式将忽略一行中的任何字符/字符串/特殊字符?