0

im trying to write a simple function to prompt for a y/n input for a given question.

#include <stdio.h>

int getChoice(char*);
int main()
{
    int a = getChoice("yes?");
    printf("%d\n",a);


    return 0;
}
int getChoice(char* msg) {
    char choice;
    printf("%s\n", msg);
    scanf("%c", &choice);
    while (choice != 'y' && choice != 'n') {
        printf("Please enter only y or n.\n");
        scanf("%c", &choice);
    }
    return choice == 'y';
}

If I enter y or n it runs as expected, but if I enter another letter, it will duplicate the line saying "Please enter only y or n.". I really cant workout where my logic goes wrong.

  • After some reading, I've worked out how to stop the repeated line. In the call to scanf, you need to call it with a ' ' before the %c. So: scanf(" %c", &choice); Can anyone tell me why this is? – user14060016 Apr 28 '21 at 06:46
  • Read about how format strings work – klutt Apr 28 '21 at 07:22

0 Answers0