验证循环

时间:2014-04-02 04:12:03

标签: 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*/

我希望用户输入一个字符,并且在验证它是ay或n之后,让它进入while循环,如果字符是ay,它将继续该程序,如果不是,它将结束它。

2 个答案:

答案 0 :(得分:2)

    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

答案 1 :(得分:1)

请注意,fflush仅针对输出流定义。在fflush上调用stdin会调用未定义的行为。您可以使用getchar函数从stdin读取和丢弃无关输入。

printf("would you like to check another time?(y/n)?");

// read and discard any number of leading whitespace characters
scanf("% c", &yesno); 
char ch;
while(yesno != 'y' && yesno != 'n') {
    // stdout is line buffered. Outputting a newline will immediately flush
    // the output to the console
    printf("That was not a valid entry, please reenter your choice.\n");

    // if the input character is not a newline, then read and discard
    // all character up till and including the newline 
    if(yesno != '\n')
        while((ch = getchar()) != '\n');  // note the null statement

    // read the input from the user afresh
    scanf("% c", &yesno);
}