stanonik@nprdc.navy.mil (Ron Stanonik) (10/18/90)
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@nprdc.navy.mil
stanonik@nprdc.navy.mil (Ron Stanonik) (10/19/90)
A thought about scanf: The scanf suppression character * means "suppress one"; ie, there had better be one to suppress, otherwise the control string isn't matched and scanning stops. But if it meant "suppress zero or one", then discarding trailing whitespace (including the newline) could be accomplished with scanf("%d%*[^\n]%*c", &i); It turns out this works in 4.3bsd, though I haven't dug into scanf yet to find out why; ie, because of a bug or because * is interpreted as "zero or one". Ron Stanonik stanonik@nprdc.navy.mil