I'm trying to understand how gets
works if it's used after scanf
.
int main()
{
char c,d;
char word[20];
int n;
printf("give a number:\n");
scanf("%d ",&n); // (input 1)
// c=getchar(); (Solution 1)
// while ((c = getchar()) != '\n' && c != EOF) ; (Solution 2)
// fflush(stdin); (Solution 3)
// gets(word); (Solution 4)
printf("Give a word:\n");
gets(word); // (input 2)
printf("word = %s ",word); // (Output)
}
I know this question is asked a lot here, and that I shouldn't use gets
at all (instead I should use fgets
). However, I have to use it since it's the only thing we were taught in class. I've read plenty of posts about it. I've found multiple solutions to evade that problem. but I still don't understand some of these solutions.
If I start my program without any of the solutions, gets
will read the new-line character \n
and won't let me give any input.
I found that this can be bypassed if I use:
(Solution 1) however let's say the user in (input 1) typed:
1 aaaaaaaaaaa \n
(Output) will be " aaaaaaaaaaa "
(Solution 2) will fix this problem and will let me give (input 2).
(Solution 3) works too; however, it's frowned upon as it doesn't have a good portability.
(Solution 4) is the same as (solution 2) I suppose. Please tell me if I'm wrong.
Another solution I found is to always use
gets
whenever I want to give input; and then format it withsscanf(...)
. Tried it! It fixed all my problems. This is what I started using.
I don't really understand Solution 2. I can see that it removes all characters besides \n
and then removes the first \n
it meets and stops the loop.
But what if the user gave this as his input
\n \n \n 1 abc \n
Why are the first 3 '\n' ignored? I don't understand the buffer notion that well.
Please let me know if I got something wrong in those solutions!
EDIT:
I already know about scanf(" %c",...);
but my problem is with gets
and not scanf
.