I’m trying to run a C program that if simplified, looks a lot like this. However, the output I’m getting if user input is other than ‘y’ and ‘n’ will run the desired output for the else statement twice. How do I fix this?
#include <stdio.h>
#include <stdlib.h>
int main(){
char input;
printf("enter input: ");
scanf("%c", &input);
if (input == 'y'){
printf("yes");
}
else if (input == 'n'){
printf("no");
}
else{
printf("redo option!\n");
main();
}
exit(0);
return 0;
}
The output looks like this for every incorrect input character received
redo option!
enter input: redo option!
enter input:
>Solution :
You need to add a space before %c in scanf like so: scanf(" %c", &input);. The space will make scanf skip the newline character which was entered.
Without this space, the newline character will be read in from the input stream and will be treated as your next character input and execution enters the else block.