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?

1
  • 2
    you need to clear stdin buffer. give the space before %c. do like scanf(" %c", &quit); Commented Dec 5, 2017 at 16:26

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.