Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly loop the program if the user input is outside of all available options?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading