When I need to scan in values from a bunch of strings, I often find myself falling back to C's sscanf()
strictly because of its simplicity and ease of use. For example, I can very succinctly pull a couple double values out of a string with:
string str;
double val1, val2;
if (sscanf(str.c_str(), "(%lf,%lf)", &val1, &val2) == 2)
{
// got them!
}
This obviously isn't very C++. I don't necessarily consider that an abomination, but I'm always looking for a better way to do a common task. I understand that the "C++ way" to read strings is istringstream
, but the extra typing required to handle the parenthesis and comma in the format string above just make it too cumbersome to make me want to use it.
Is there a good way to either bend built-in facilities to my will in a way similar to the above, or is there a good C++ library that does the above in a more type-safe way? It looks like Boost.Format has really solved the output problem in a good way, but I haven't found anything similarly succinct for input.
printf
with variadic templates is pretty easy, apart from positional arguments. I would expect the same issue withsscanf
. Apart from that, I do not see an issue in performance. If anything, partial inlining could really be beneficial here.Boost.Format
does the equivalent ofprintf
already, though with an awkward syntax as it was created before the variadic templates, but I don't know of a scanning library.operator>>
forstd::complex<double>
will read exactly this format.