H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Jan 13 16:15:55 PST 2012
On Fri, Jan 13, 2012 at 11:05:19PM +0100, Matej Nanut wrote:
> While we're at it: what's the best way to parse in a formatted manner?
> For example, if I want to get 5 hexadecimal digits converted into an
Have you tried:
uint val = parse!uint(input_string[0..5], 16);
> And I want to simultaneously advance the string?
You can always keep track of how many characters were consumed by
parse() and advancing the string yourself. Something like this:
string tmp = input_string[0..5];
uint val = parse!uint(tmp, 16);
input_string = input_string[5-tmp.length .. $];
If you find this a bit verbose, you can always encapsulate it in a
function and use that instead.
> "sscanf" seems fiddly and unsafe.
IMNSHO, sscanf is one of the poorest designed functions we had the
misfortune to inherit from the C library. It pretends to mirror printf()
in its format string, but the semantics are subtly different and likes
to come back to bite you unexpectedly at the most inopportune times (if
you ever tried using "%s" to read back a string printed using "%s", or
tried to count embedded spaces in the input, you'll know what I mean).
In C and C++ (can't speak for the D wrappers for it) it also suffers
from potential buffer overruns, pointer bugs, and all sorts of other
lovely things. It seems so nice and simple to use, but comes with all
sorts of nasty gotcha's, bad corner cases, etc..
I say, avoid sscanf like the plague. There are many other much better
Klein bottle for rent ... inquire within. -- Stephen Mulraney
More information about the Digitalmars-d-learn