I was trying to solve the newline buffer problem when using fgets() after scanf() and my initial solution was to consume the newline with scanf("\n"); and it solved the problem, but then i encountred a different solution to consume the newline in buffer with scanf("%c ",&ch);
note: there is a space after %c that did solve the problem
this is the complete code that results a newline buffer problem:
#include "stdio.h"
int main() {
char ch;
char s[100];
char sen[100];
scanf("%c", &ch);
scanf("%s", s);
fgets(sen, sizeof(sen), stdin);
printf("%c\n", ch);
printf("%s\n", s);
puts(sen);
return 0;
}
But the same code will work when adding space after %c and %s as follows:
#include "stdio.h"
int main() {
char ch;
char s[100];
char sen[100];
scanf("%c ", &ch);
scanf("%s ", s);
fgets(sen, sizeof(sen), stdin);
printf("%c\n", ch);
printf("%s\n", s);
puts(sen);
return 0;
}
My question is how did the two spaces after %c and %s did consume the newline to make it possible for fgets() to take the input?