formattedRead whitespace quirks (compared to scanf)
Ali Çehreli
acehreli at yahoo.com
Wed Dec 25 13:06:45 PST 2013
On 12/25/2013 12:43 PM, Gordon wrote:
> -- in C --
> char a[100] = {0};
> chat *input = "hello world 42";
> sscanf(input, "%s", &a);
> -- in D --
> string a;
> string input = "hello world 42";
> formattedRead(input,"%s", &a);
> -----------
>
> In "C", the variable "a" would contain only "hello";
> In "D", the variable "a" would contain "hello world 42";
>
> BUT,
> If the format string would be "%s %s %d" (and we had three variables),
> then "formattedRead()" would behave exactly like "sscanf()".
That is by design. Since a string can contain space characters, the
normal behavior is to read everything as a part of the the string. scanf
is defined differently.
However, just like scanf, a space character in the format string matches
zero or more whitespace characters in the input and ignores them. So,
"%s %s %d" means to read and ignore the spaces between the three data
that you are reading.
By the way, you almost never need anything but %s in D; unlike scanf,
formattedRead() actually knows the exact types of its parameters, so %s
works for integers as well.
Ali
More information about the Digitalmars-d
mailing list