Re: Converting a substring to Integer
James Kanze <james.kanze@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.
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.
|