readf with strings

Ali Çehreli acehreli at yahoo.com
Wed Jun 22 11:20:48 PDT 2011


On Wed, 22 Jun 2011 20:59:46 +0300, Dainius (GreatEmerald) wrote:

> I see. Using %s does indeed work with ints, and chomp(readln()) works
> with strings. It's rather counter-intuitive, though.

There are many counter intuitive bits and imperfect modelling in stream I/
O. For example "42a" is perfectly fine when reading an int because the 
reader decides that the '4' and '2' characters make up the int and 'a' 
must be for something else. Why? :) What if I really meant that "42a" 
should be read as int. It should be an error!

I think strings are special because they are powerful to take any 
character.

Additionally output and input are not symmetrical: The ints 1 and 2 would 
be written as 12 back to back but they can't be read as two ints.

> I wonder why there
> isn't a simpler way to do this, something like writeln() - you could
> input the variables as parameters and it would automatically read
> them...

I know that the insistence on the space character to munch white space is 
intentional. Andrei commented on a bug that this is more consistent than 
scanf()'s implicit munching.

There is <cstream> that is being (is?) deprecated. It reads simpler like 
writeln:

import std.cstream;

void main()
{
    double d;
    int i;
    din.readf(&d, &i);
    dout.writefln("d: %s, i: %s", d, i);
}

It would still be problematic with strings. How many characters should be 
a part of it?

Ali


More information about the Digitalmars-d-learn mailing list