Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this loop with scanf always quit?

Tags:

c

#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?

like image 898
Angus87 Avatar asked Aug 04 '26 09:08

Angus87


1 Answers

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);
like image 119
dbush Avatar answered Aug 06 '26 03:08

dbush