Is there a convenient way to parse an integer from a string::iterator
in c++? For this specific question I only care about nonnegative base 10 integers, but all of these solutions can be pretty easily extended to arbitrary integers. Note, unlike similar questions I don't have a reference to the original string, only an iterator, e.g.
int parse_next_int(std::string::iterator begin, std::string::iterator end) {
// ...
}
I can think of a number of ways, but none are great. Another note, I'm not declaring stl headers, and I'm assuming everything is done in the std
namespace. Hopefully this won't make the examples too difficult to parse.
Allocate a new string, and then call stoi:
int parse_next_int(string::iterator begin, string::iterator end) { string::iterator num_end = find_if( begin, end, [](char c)->bool{return !isdigit(c);}); string to_parse(begin, num_end); return stoi(to_parse); }
The downside of this is that I end up allocating a new buffer for something that could presumably be parsed on the fly.
Treat unsafely as a c string.
int parse_next_int(std::string::iterator begin, std::string::iterator end) { return atoi(&(*begin)); }
This will somewhat work, but if it hits the end of the string and it's not not null terminated (which isn't guaranteed with c++ strings) it will segfault, so while nice and concise, this is probably the worst.
Write it myself:
int parse_next_int(std::string::iterator begin, std::string::iterator end) { int result = 0; while (begin != end && isdigit(*begin)) { result = result * 10 + (*begin++ - '0'); } return result; }
This works and is simple, but it's also heavily problem dependent and not very error tolerant.
Is there some significantly different method that mostly relies on more tolerant stl calls, while still being simple and avoids copying unnecessary buffers?