Equivalent of scanf

Jonathan M Davis jmdavisprog at gmail.com
Sat Jul 17 15:59:55 PDT 2010


On Saturday 17 July 2010 15:41:14 Michael Koehmstedt wrote:
> I'm having trouble figuring out how to do formatted console input,
> something like C scanf() or C++ templated stream input. Unfortunately,
> console input isn't covered in much detail in TDPL book. There doesn't
> appear to be much discussion about the standard library at all, which was
> a bit disappointing.
> 
> But anyway, what different ways are there to properly do input from the
> console? Fetching a string with readln() is easy enough, but how could I
> fetch, say, an integer value? Conversely, what is the preferred method for
> converting string into integer or floating point values?
> 
> Thanks,
> Michael

Parsing strings like that isn't something that I've done much of lately, so I 
don't know what the best way to do it in D is. However, std.conv has essentially 
what you're looking for. For most conversions, just use to!T() - e.g. 
to!int(str) will convert the string str into an int and to!string(i) will 
convert the integer i to a string. For more complicated parsing, there's 
parse!T() which does essentially the same thing except that instead of 
converting the whole string, it only converts the portion which makes sense and 
leaves the rest. e.g.

string test = "123 \t  76.14";
auto a = parse!(uint)(test);
assert(a == 123);
assert(test == " \t  76.14");

So, with multiple calls to parse, you can parse the string. I'm not aware of a 
way to do it in manner like sscanf though, where you parse it all in one 
command. Worse comes to worse, if you really want that, you can always use C's 
sscanf and it'll work.

TDPL purposely didn't touch on Phobos much. One reason for this is because it 
was focusing on the language itself rather than whatever libraries there might 
be. The other main reason, as I understand it, is that Phobos has been in too 
much flux to have put in TDPL. A lot of work has been done on Phobos in the past 
few months, and TDPL was already turned in to the editor. And a lot of work 
continues to be done on Phobos. So, anything that was put in TPDL on Phobos 
would either have constrained Phobos so that it couldn't change when it needed 
to or would have made it so that TDPL didn't match Phobos - either that or we 
would have had to wait longer for TDPL.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list