Substitute for gets()

Karl Heuer karl at haddock.ima.isc.com
Tue Feb 14 05:29:35 AEST 1989


In article <722 at hscfvax.harvard.edu> xmjschm at hscfvax.UUCP (R00100 at MJSchmelzer) writes:
>One final question: No one mentioned scanf("%255s", buffer) [as a gets()
>replacement].  This _does_ seem wrong to me, but I can't quite pin it down.
>Comments?

I guess my mail didn't get through.  %s is wrong because it scans a token
rather than a line, but I did mention
	scanf("%254[^\n]%*c", buffer)
as a possible solution.  (I used 254 since you said the buffer was char[255],
and we need one byte for the trailing \0.)  This no longer crashes on long
lines, but it still fails to detect them.  (This could be fixed via
	char ch;
	if (scanf("%254[^\n]%c", buffer, &ch) != 2 || ch != '\n') error();
, but fgets() seems cleaner.)

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list