santosh skrev:
vamshi wrote:
char str[20];
[...]
scanf("%[^a]",str);
scanf() is second only to gets() in being unsuited for string input.
scanf() can be difficult to use correctly for beginners,
OP's broken way can be fixed:
scanf("%19[^a]", str);
is "safe", since it will not overflow 'str'.
OP, might want to remove the end-of-record marker 'a', with:
scanf("%19[^a]", str);
getchar();
Furthermore, for robust code, the return value of scanf()
need to be checked (see below).
fgets() is better suited for this job.
Well, try to write this with fgets():
char line[81];
int n;
n = fscanf(stdin, "%80[^\n]%*[^\n]", line)
getchar(); /* throw away '\n' */
:-)
Above is a safe and simple way to read the first 80
char's of a line with unknown lenght. For error-checking,
we have:
case n == 1: line has been scanned
case n == 0: empty, i.e. no characters before '\n'
case n == EOF: EOF or I/O error before '\n', check with feof()/ferror()
A function like CBFalconer's ggets(), (search the group for source), is
even better.
Well, IIRC, ggets() used malloc/realloc, which I usually hate.
Wouldn't use it for cases where I need robust code. The
point is that ggets() is a potential DoS [1] security hole, since
it will grab all available memory...
R.H. fgetdata() has a 'maxrecsize' parameter, which makes
it more robust, see:
http://users.powernet.co.uk/eton/c/fgetdata.html
where can this be used?
Ideally nowhere.
I have used it and will continue to do so, for example:
fscanf(stdin,"%*[^\n]");
when I just want to "eat" until the end-of-line.
how exactly it is working?
Implementation and platform specific. Ask in the appropriate group.
AFAIK, the usage of circumflex (^) in a scanlist is
well-defined, it's rather the usage of (-) which is
implementation specific.
--
Tor
[1] DoS = Denial of Service