Search code examples
c++boostlexical-cast

boost lexical_cast throws exception


I'm using boost libs for c++ and the function lexical_cast behaves really weird. If I do lexical_cast("0.07513994") it works fine, but if I use my variable which I need to convert, it throws the bad_lexical_cast exception. Here is the code:

string word;
istringstream iss(line);
do
{
   string word;
   iss >> word;        
   double x;
   x = lexical_cast<double>(word);   
   cout << x << endl;
} while (iss);

What am I doing wrong here? I appreciate any help, thanks


Solution

  • Your problem is probably that the loop is processed one more time than you expect. The last time through the loop, the read to word fails, setting the fail bit in iss, which is what while(iss) is checking. To fix it you need to do something like this.

    string word;
    istringstream iss(line);
    do
    {
       string word;
       iss >> word; 
       if(iss)
       {       
         double x;
         x = lexical_cast<double>(word);   
         cout << x << endl;
       }
    } while (iss);