Re: Converting a substring to Integer
On Feb 7, 2:33 pm, Reetesh Mukul <reetesh.mu...@gmail.com> wrote:
On Feb 7, 5:20 pm, "Daniel T." <danie...@earthlink.net> wrote:
James Kanze <james.ka...@gmail.com> wrote:
Reetesh Mukul <reetesh.mu...@gmail.com> wrote:
"Daniel T." <danie...@earthlink.net> wrote:
ReeteshMukul <reetesh.mu...@gmail.com> wrote:
Actually, I assumed that numeric-digits will appear
surrounded by space.
I still don't see why you had to make the procedure so
complex.
Your code is emulated by the code below, which is far simpler:
int main()
{
std::string s = "dsdhjsahdk dsdjdsaj 36782367 sdjdhak";
int result = 0;
std::stringstream cstr( s );
char ch = 0;
while ( cstr >> ch && !isdigit( ch ) )
cstr.ignore( numeric_limits<streamsize>::max(), ' ' );
cstr.putback( ch );
cstr >> result;
cout << result;
}
Yes, this is a great solution. Very simple and compact solution.
It fails if the separator is a tab, rather than a space.
The code has lots of assumptions and it fails if any of them
don't hold, that's not the point.
Yes and no. IMHO, the point is that this is generally not a
good way to parse input. The ignore function is not flexible
enough to be generally of much use other than for
resynchronizing the input after an error (and even then, only
with very simple formats).
The question I asked Reetesh was why he had such a complex
solution when the above solution, which is far simpler, does
the exact same thing. I'm guessing that it was because he
didn't know about the 'ignore()' member-function, and didn't
know that the putback and op>> would do the "right thing" if
the stream failed.
Yes, you are right Daniel. I indeed didn't knew about
'ignore()' and putback,op's mechanism after things fail. Now
an obvious question is popping in my mind, will it not be good
to have predicates( functors ) in ignore function (or similar
functions) ?
Probably because that's not its role. But it's an interesting
suggestion---it should be possible to define a manipulator which
skips using a predicate. More useful, probably, would be a
manipulator which skips using a regular expression. This would
be far from trivial with extended regular expressions, like
Boost (which requires at least a forward iterator, since
backtracking is necessary), but wouldn't be too hard with my
regular expression class, which doesn't support any of the
extensions, but will work with input iterators.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34