The difference in string and char[], readf() and scanf()

Ivan Kazmenko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 21 16:00:44 PDT 2015


On Saturday, 21 March 2015 at 16:34:44 UTC, Dennis Ritchie wrote:
> And why in D copied only the first 32767 characters of the 
> string? I'm more days couldn't understand what was going on...

To me, it looks like a bug somewhere, though I don't get where 
exactly.  Is it in bits of DigitalMars C/C++ compiler code glued 
into druntime?

Anyway, as for Codeforces problems, you mostly need to read text 
input as tokens separated by spaces and/or newlines.  For that, D 
I/O is sufficient, there is no need to use legacy C++ I/O.

Usually, readf(" %s", &v) works for every scalar type of variable 
v (including reals and 64-bit integers) except strings, and 
readln() does the thing for strings.  Don't forget to get rid of 
the newline sequence on the previous line if you mix the two.  
Possible leading and trailing spaces in " %s " mean skipping all 
whitespace before or after the token, respectively, as is the 
case for scanf in C/C++.

As far as I remember, for reading a line of numbers separated by 
spaces,
-----
auto a = readln.split.map!(to!int).array;
-----
is a bit faster than a loop of readf filling the array, but that 
hardly matters in the majority of problems.  You can see my 
submissions (http://codeforces.com/submissions/Gassa) for example.

If you really feel the need for I/O better suited for the 
specifics of algorithmic programming contests (as Java people 
almost always do in their language for some reason), look at 
Kazuhiro Hosaka's submissions 
(http://codeforces.com/submissions/hos.lyric).

In case you want to go even further and write your own I/O layer 
for that, I'll point you to a recent discussion of text I/O 
methods here: http://stackoverflow.com/q/28922323/1488799 (see 
comments and answers).

Ivan Kazmenko.


More information about the Digitalmars-d-learn mailing list