3
#include <stdio.h>

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf("%c", &quit);
  }while(quit=='n' || quit=='N');
}

Why does my program quit after inputting anything?

dbush
  • 205,898
  • 23
  • 218
  • 273
Angus87
  • 45
  • 4
  • 2
    you need to clear stdin buffer. give the space before %c. do like scanf(" %c", &quit); – Achal Dec 05 '17 at 16:26

2 Answers2

7

The %c format specifier accepts any character, including newlines. So if you press N, then scanf reads that character first but the newline from pressing ENTER is still in the input buffer. On the next loop iteration the newline character is read. And because a newline is neither n or N the loop exits.

You need to add a space at the start of your format string. That will absorb any leading whitespace, including newlines.

scanf(" %c", &quit);
dbush
  • 205,898
  • 23
  • 218
  • 273
1

Just change your code to:

#include <stdio.h>

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf(" %c", &quit);
  }while(quit=='n' || quit=='N');
}

For more information read this link

Lalit Verma
  • 782
  • 10
  • 25