DN> fgets() is only a little extra typing, and performs the
DN> same functionality and is safe because you can limit
DN> input (although exactly what you do with characters after
DN> the 99th is up to you). There is also no reason to assume
DN> that stdin is a terminal/keyboard - someone may have
DN> redirected it from elsewhere.
KH> Yes, but isn't gets() taking from the stdin anyway?....
Sure, it's always taken from stdin, but what if stdin is a file? That's
what I was saying:
program so either way fgets(buffer,100,stdin); would be roughly
KH> the same as gets(buffer); except for lengths...
Yes. But that "except for ..." is not trivial, however. :-)
DN> Summary: gets() is dangerous - don't use it.
KH> Thanx, I have never seen anyone elsewhere being warned
KH> about this, so I would have continued to use that
KH> dangerous little command :).. fixed it up or anything like that??>..
The problem is that it was made part of the ANSI standard back in 1989 with
lots of legacy C code exiting at the time that used gets(). Consequently,
any ANSI/ISO conforming compiler must supply it.
I'm surprised you haven't seen warnings though - most compiler vendors
actually *do* say something about this in the documentation.
KH> and any idea
KH> what's the story on using fscanf over scanf?.. I heard
KH> that fscanf is safer or something...
No idea on that one - implementations vary widely, but I'd be surprised if
scanf() differed much from fscanf() from stdin.
The scanf() functions are difficult to use at best, and something probably
best avoided by a novice user (use fgets()). They are, however, quite
powerful parsing functions and can be pretty useful if used correctly -
they can reduce a lot of complex parsing code to a single line of code. If
you're just grabbing strings, then I'd suggest sticking with something
simple like fgets(). Even grabbing numbers is easier with fgets() and
atoi/atol (or similar) - the *scanf() form of input usually has some
undesirable side-effects when use interactively since it stops at the first
non-numeric character when looking for numeric input and so on, so you can
easily flush the input stream, prompt again and get fresh input and so on.
Besides, if you grab a line of input, you can always parse it with
sscanf(). This is the approach I've always preferred since you're not
fiddling about with stdio file states and don't have to worry about left
over data.
--- MaltEd/2 1.0.b6
* Origin: Decadence BBS & Unique Computing - What a team! (3:632/348)
SEEN-BY: 50/99 620/243 623/630 632/103 348 360 998 633/371 634/384 388
SEEN-BY: 635/301 502 503 544 727 639/252 711/401 409 410 413 430 510 808 809
SEEN-BY: 711/932 934 712/515 713/888 714/906 800/1 7877/2809
@PATH: 632/348 635/503 50/99 711/808 809 934
|