I have been told that scanf should not be used when user inputs a string. Instead, go for gets() by most of the experts and also the users on StackOverflow. I never asked it on StackOverflow why one should not use scanf over gets for strings. This is not the actual question but answer to this question is greatly appreciated.
Now coming to the actual question. I came across this type of code -
scanf("%[^\n]s",a);
This reads a string until user inputs a new line character, considering the white spaces also as string.
Is there any problem if I use
scanf("%[^\n]s",a);
instead of gets?
Is gets more optimized than scanf function as it sounds, gets is purely dedicated to handle strings. Please let me know about this.
Update
This link helped me to understand it better.
gets
isn't a very good idea either because of the risk of buffer overflows. Usefgets
. – Borschfgets
by passingstdin
as the last parameter. The advantage of usingfgets
overgets
is that withfgets
, you can specify the length of your buffer, preventingfgets
from reading too much data.gets
is a security risk, and they never fixed it for backward compatibility reasons. – Borschf*
function (say,fscanf
) can be used on thestdin
filehandle to emulate the non-f*
version (in this case,fscanf(stdin, ...)
is exactly equivalent toscanf(...)
). – Livornostdin
will always wait for a newline. However, if the user enters more characters thanfgets
asked for, they are stored in a buffer as part of theFILE *
structure, and not to be accessed by you. A second call tofgets
will, instead of reading more user input, return more data from that buffer, until it is empty. (fgetc
the other one-character-at-a-time functions do the exact same thing.) – Livornogets()
. It cannot be used safely. It's even being removed from the next version of the C standard. – Grandpagets_s
(new in C11 standard) which allows you to safely read from standard input to a buffer without the hassle of stripping ending newline characters. – Saarinengets
was removed in C11, yes. Some implementations might still have it, however. The standard alternative since C11 isgets_s
. – Borsch