scanf/discarding remaining whitespace

Ron Stanonik stanonik at nprdc.navy.mil
Thu Oct 18 04:26:17 AEST 1990


Probably an oft repeated question.

How can one scanf, say an integer, and discard trailing whitespace
(include the newline)?  There might be no trailing spaces/tabs; ie,
only a newline.  (This is on suns running sunos4.1 and a vax running
4.3bsd.)

scanf("%d", &i) leaves the trailing spaces/tabs and newline on the input.

scanf("%d%*[ \t]", &i) leaves the newline on the input.

scanf("%d%*[ \t]%*c", &i) leaves the newline if there are no trailing
spaces/tabs on the input; ie, %*[ \t] fails, so the newline is left on
the input.

The only solutions I know of require a separate gets; eg,
	scanf("%d", &i);
	gets(temp);
or
	gets(temp);
	sscanf(temp, "%d", &i);

This seems like a clumsy solution to what must be a common need,
scanf, discarding everything up to and including the next newline.
How often do you want to leave trailing whitespace (including the
newline) on the input?

Thanks,

Ron Stanonik
stanonik at nprdc.navy.mil



More information about the Comp.unix.questions mailing list