Discussion: static istringstream
Afficher un message
Vieux 07/06/2008, 18h19   #3
Abhishek Padmanabh
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: static istringstream

On Jun 7, 7:51pm, Abhishek Padmanabh <abhishek.padman...@gmail.com>
wrote:
> On Jun 7, 5:36pm, sergey.lukosh...@gmail.com wrote:
> > My task is in converting numbers from string to int variables. I used
> > istringstream to perform it.
> > So I wrote simple test function. But it doesn't work as I expected
> > because val is not being changed while the program is running. Could
> > you please tell me why ??

>
> > #include <iostream>
> > #include <sstream>
> > #include <iomanip>
> > #include <stdint.h>

>
> > int main()
> > {
> > static std::string str;
> > static std::istringstream istr;
> > static unsigned val;

>
> > while( true )
> > {
> > std::cout << "Enter num: " << std::endl;
> > std::cin >> str;

>
> > istr.str(str);

>
> > istr >> val;
> > std::cout << "Number: " << val << std::endl;
> > }

>
> > return 0;
> > }

>
> You need to clear the buffer held by the stringstream object. Make a
> call istr.str("");


Sorry, correction : it seems eof() bit is being set for the
stringstream. And hence it further doesn't work. You need to clear
that flag for the next iteration. For that, you need to call the
clear() member. Verified that by putting in:

std::cout << std::endl << istr.eof() << " " << istr.fail() << " "
<< istr.bad() << std::endl;

You need to check those flags, eof() may be ok but if the rest of the
2 bits are set then that would probably mean an error with the IO
operation.

> Alternatively, why don't you use boost::lexical_cast<> which is just a
> header only library from boost? Saves you from error handling routines
> as well which otherwise you need to employ yourself for cases where it
> fails.

  Réponse avec citation
 
Page generated in 0,06015 seconds with 9 queries