Discussion:
Bad Lexical_Cast!
Frame Buffer
2007-08-22 14:23:19 UTC
Permalink
Hello!

I am trying to compile the following program from *Beyond the C++ Standard
Library: An Introduction to Boost.

*Here is the source code:

#include <iostream>
#include <string>
#include "boost/lexical_cast.hpp"

class lexical_castable
{
public:
lexical_castable()
{

};

lexical_castable(const std::string s) :
s_(s)
{

};

friend std::ostream& operator<<(std::ostream& o, const lexical_castable&
le);
friend std::istream& operator>>(std::istream& i, lexical_castable& le);

private:
virtual void print_(std::ostream& o) const;
void read_( std::istream& i );
std::string s_;
};

std::ostream& operator<<(std::ostream& o, const lexical_castable& le)
{
le.print_(o);

return o;
}

std::istream& operator>>(std::istream& i, lexical_castable& le)
{
le.read_(i);

return i;
}

void lexical_castable::read_( std::istream& i )
{
i >> s_;
}

void lexical_castable::print_( std::ostream& o ) const
{
o << s_ <<"\n";
}

int main(int argc, char* argv[])
{
lexical_castable le();
std::cin >> le;

int i=0;

try
{
i = boost::lexical_cast<int>(le);
std::cout << i << '\n';

}
catch(boost::bad_lexical_cast &e)
{
std::cout << e.what() << '\n';

std::cout << "You were supposed to enter a number!\n";
}
}

The lexical_cast is throwing an exception as follows:

‡ boost::bad_lexical_cast::what returned 0x004c9888 "bad lexical
cast: source type value could not be interpreted as target" const char *

Note that I have modified the original code a bit because I was trying to
figure out what went wrong. The object le is getting created successfully
with the user entered "number" getting stored in the string s_

Please help. I am using Visual studio 2005 with boost v1.34
Frank Birbacher
2007-08-22 23:12:53 UTC
Permalink
Hi!
Post by Frame Buffer
void lexical_castable::print_( std::ostream& o ) const
{
o << s_ <<"\n";
}
This newline here makes the cast fail because the lexical_cast requires
the target type to consume all characters. But a newline does not help
making an int. Remove the newline to make the cast work.

Frank

Continue reading on narkive:
Loading...