سؤال

This was originally from another program, but this segment will not work the way I need it to and I imagine others may be having trouble as well. Also of note that after the user input is accepted it is used in a while loop.

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

I want the user to input a character, and after verifying it is either a y or an n, have it go to a while loop where if the character is a y it will continue the program, and if not it will end it.

هل كانت مفيدة؟

المحلول

    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 ...

additional

I just noticed another crucial failure that is affecting your snippet (and i imagine the next lines of codes also )

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

نصائح أخرى

Please note that fflush is defined only for output streams. Calling fflush on stdin is invokes undefined behaviour. You can use getchar function to read and discard extraneous input from the 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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top