Formatted read consumes input
Steven Schveighoffer
schveiguy at yahoo.com
Fri Sep 7 06:59:05 PDT 2012
On Thu, 23 Aug 2012 07:33:13 -0400, monarch_dodra <monarchdodra at gmail.com>
wrote:
> As title implies:
>
> ----
> import std.stdio;
> import std.format;
>
> void main()
> {
> string s = "42";
> int v;
> formattedRead(s, "%d", &v);
> writefln("[%s] [%s]", s, v);
> }
> ----
> [] [42]
> ----
>
> Is this the "expected" behavior?
>
> Furthermore, it is not possible to try to "save" s:
> ----
> import std.stdio;
> import std.format;
> import std.range;
>
> void main()
> {
> string s = "42";
> int v;
> formattedRead(s.save, "%d", &v);
> writefln("[%s] [%s]", s, v);
> }
> ----
> main.d(9): Error: template std.format.formattedRead does not match any
> function template declaration
> C:\D\dmd.2.060\dmd2\windows\bin\..\..\src\phobos\std\format.d(526):
> Error: template std.format.formattedRead(R,Char,S...) cannot deduce
> template function from argument types !()(string,string,int*)
> ----
>
> The workaround is to have a named backup:
> auto ss = s.save;
> formattedRead(ss, "%d", &v);
>
>
> I've traced the root issue to formattedRead's signature, which is:
> uint formattedRead(R, Char, S...)(ref R r, const(Char)[] fmt, S args);
>
> Is there a particular reason for this pass by ref? It is inconsistent
> with the rest of phobos, or even C's scanf?
>
> Is this a file-able bug_report/enhancement_request?
I believe it behaves as designed, but could be designed in such a way that
does not need ref input range. In fact, I think actually R needing to be
ref is a bad thing. Consider that if D didn't consider string literals to
be lvalues (an invalid assumption IMO), then passing a string literal as
the input would not work!
The only issue is, what if you *do* want ref behavior for strings? You
would need to wrap the string into a ref'd range. That is not a good
proposition. Unfortunately, the way IFTI works, there isn't an
opportunity to affect the parameter type IFTI decides to use.
I think a reasonable enhancement would be to add a formattedReadNoref (or
better named alternative) that does not take a ref argument.
-Steve
More information about the Digitalmars-d
mailing list