Search code examples
d

can't readf to the same variable twice


For this simple code:

long l;
readf("%d", &l);
readf("%d", &l);

when I enter 20 as the second number it throws an exception

exception: std.conv.ConvException@/usr/include/dlang/dmd/std/conv.d(1995): 

Unexpected '2' when converting from type LockingTextReader to type long

Why is this happening and what am I doing wrong?


Solution

  • There's still a newline sitting in the buffer after the first one that needs to be consumed.

    Similar to what I wrote about here: D lang - Using read and readln() in the same program

    the same fix should work.

    long l;
    readf(" %d", &l); // note the leading space
    writeln("Got ", l);
    readf(" %d", &l); // and again
    writeln("Got ", l);