Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a line using scanf() not good?

Tags:

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?

like image 245
amulous Avatar asked Jun 25 '13 10:06

amulous


People also ask

What is the problem with scanf () to read a string?

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.

What is the limitation of using scanf in reading strings?

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.

How a line can be read using scanf () function?

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').

Why is scanf not reading input?

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.


1 Answers

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[]).

like image 85
Grijesh Chauhan Avatar answered Oct 16 '22 22:10

Grijesh Chauhan