0

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:
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Wisnu.wdn
  • 41
  • 3
  • 2
    Recursion is almost never an appropriate solution. Don't call `main` from `main`. Write a loop. I've removed the C++ tag because the question is explicitly about C and because calling `main` from anywhere inside a program is illegal in C++. – Pete Becker Dec 15 '21 at 16:17
  • 1
    `scanf` with `%c` is also reading the newlines that result from your hitting the Enter key. Try using `" %c"` (note the extra space). That'll tell `scanf` to skip whitespace, which is almost always what you want. – Steve Summit Dec 15 '21 at 16:19

2 Answers2

1

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.

babon
  • 3,615
  • 2
  • 20
  • 20
0

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.
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115