scanf(" %[^\n]",line);
A friend of mine suggested that using fgets()
to read a line as input would be a much better idea than using scanf()
as in the statement above. Is he justified?
Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program. 2) The similar problem occurs when scanf() is used in a loop.
The problems with scanf are (at a minimum): using %s to get a string from the user, which leads to the possibility that the string may be longer than your buffer, causing overflow. the possibility of a failed scan leaving your file pointer in an indeterminate location.
When using printf() to display the input of the user you use a normal "%s" sign, the "%[^\n]%*c" is only used with scanf() since this function takes input only till the first space. Show activity on this post. Keep taking input character by character till you find a newline('\n').
Rule 1: scanf() is not for reading input, it's for parsing input. The first argument to scanf() is a format string, describing what scanf() should parse. The important thing is: scanf() never reads anything it cannot parse. In our example, we tell scanf() to parse a number, using the %d conversion.
char * fgets ( char * str, int num, FILE * stream );
is safe to use because it avoid buffer overflow problem, it scans only num-1
number of char.
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
here second argument num
is Maximum number of characters to be copied into str (including the terminating null-character).
For example suppose in your code a string array capacity is just 5
chars long as below.
char str[5]; fgets (str, 5, fp); //5 =you have provision to avoid buffer overrun
Using above code, if input from fp
is longer then 4
chars, fgets()
will read just first 4
chars then appends \0
(, and discard other extra input chars, just stores five char in str[]
).
Whereas scanf(" %[^\n]",str);
will read until \n
not found and if input string is longer then 4
chars scanf()
will cause of buffer overflow (as scanf
will try to access memory beyond max index 4
in str[]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With