After the call, scanf("%d", &variable);we are left with a new line hanging on stdin, which must be cleared before the call fgets, or we end up giving it a new line and making it return prematurely.
I found answers, offering to use scanf("%*[^\n]%*c");after the first call scanfto cancel a new line, while others suggested using scanf("%*[^\n]\n");. Theoretically, both should work: the first will consume everything that is not a new line (but does not include the new line itself), and then consumes exactly one character (new line). The second will consume everything that is not a newline character (not including it), and then \n, whitespace character, instructs scanfto read all whitespace characters to the first character without spaces.
However, as it seems to me, these approaches work in some answers, I could not get them to work here (codes below).
Why didn't any of the approaches scanfwork?
Tested: Ubuntu Linux - gcc5.4.0
scanf("%*[^\n]\n");:
#include <stdio.h>
int main(int argc, char **argv){
int number;
char buffer[1024];
printf("Write number: \n");
scanf("%d", &number);
scanf("%*[^\n]\n");
printf("Write phrase: \n");
fgets(buffer, 1024, stdin);
printf("\n\nYou wrote:%u and \"%s\"\n", number, buffer);
return 0;
}
Conclusion:
$ ./bug
Write number:
2
Write phrase:
You wrote:2 and "
"
scanf("%*[^\n]%*c");:
#include <stdio.h>
int main(int argc, char **argv){
int number;
char buffer[1024];
printf("Write number: \n");
scanf("%d", &number);
scanf("%*[^\n]%*c");
printf("Write phrase: \n");
fgets(buffer, 1024, stdin);
printf("\n\nYou wrote:%u and \"%s\"\n", number, buffer);
return 0;
}
Conclusion:
$ ./bug2
Write number:
3
Write phrase:
You wrote:3 and "
"
, , :
:
#include <stdio.h>
int main(int argc, char **argv){
int number;
char buffer[1024];
printf("Write number: \n");
scanf("%d", &number);
int c;
while((c = getchar()) != '\n' && c != EOF){
}
printf("Write phrase: \n");
fgets(buffer, 1024, stdin);
printf("\n\nYou wrote:%u and \"%s\"\n", number, buffer);
return 0;
}
:
$ ./notbug
Write number:
4
Write phrase:
phrase :D
You wrote:4 and "phrase :D
"