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

Time:12-16

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:

CodePudding user response:

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.

CodePudding user response:

You probably want this:

#include <stdio.h>
#include <stdlib.h>

int main() {
  char input;

  do
  {
    printf("enter input: ");
    scanf(" %c", &input);    // note the space before %c
    if (input == 'y') {
      printf("yes\n");
    }
    else if (input == 'n') {
      printf("no\n");
    }
    else {
      printf("redo option!\n");
    }
  } while (1);               // loop forever
}
  • Use a simple infinite loop instead of calling main recursively
  • the space before the %c in " %c" prevents the line ending itself to be read as characters.
  •  Tags:  
  • c
  • Related