Am aware that the difference between scanf() and gets() function is that scanf() continues to read the input string until it encounters a whitespace, whereas gets() continues to read the input string until it encounters a \n or EOF(end of file).
To see this difference in action, I tried writing a example on my own which is as follows:
#include <stdio.h>
int main()
{
char a[20];
printf("enter the string\n");
scanf("%s",&a);
printf("the string is %s\n",a);
char b[20];
printf("enter the string\n");
gets(b);
printf("the string is %s\n",b);
return 0;
}
When the variable a was given the string "manchester united" as input, the output was:
enter the string
manchester united
the string is manchester
enter the string
warning: this program uses gets(), which is unsafe.
the string is united
What I was expecting as output was just the first part of the string given to the variable a which is manchester and then, the program prompting me to enter the new input string for the variable b. Instead, I ended up with the above given output.
Based on the output, what I understand is:
It can be seen that as soon as scanf() encounters the whitespace, it stops reading the string thereafter, and thus, the remaining part of the string:united, has been assigned to the variable b,even without the program prompting me to enter the string for variable b.
How do I flush out the remaining part(the portion after the whitespace) of the string given to variable a?
so that, I can enter a whole new input string for the variable b.
Any further explanation on what is also happening here in the execution of the code will be greatly appreciated.
Apologies for the very basic mistakes(as it is evident by the responses)!! Just a novice to C programming:)
gets()
should not be used and it has been deprecated in recent versions of the c standard. Your code has also multiple other issues like using&
operator to pass an array for a"%s"
specifier toscanf()
. If the compiler, (or runtime?, since I would never usegets()
I didn't know there was a warning) is issuing a warning why do you keep using it? – Iharob Al Asimigets
! It has even been removed from the C standard, which is really a rare event. – too honest for this sitescanf("%s",b)
==gets(b)
== a hole through which your user may crash or take control of your program – PSkociksscanf
to parse the line you read. – David Schwartz&
operator to pass an array for a"%s"
specifier toscanf()
invokes undefined behaviour ? I think so !!! – Destructor