Re: Howto identify a string value vs. a numeric value in std::string
frohlinger@gmail.com wrote:
Thanks, but I'm not sure I can use libraries, except MFC.
This is a dll, part of a bigger product at work, with restrictions.
Boost libraries are not Microsoft's, right?
Gabi.
#include <sstream>
#include <iostream>
#include <typeinfo> // bad_cast
template <class To, class From>
To LexicalCast(From const& from)
{
std::ostringstream oss;
oss << from;
if (!oss)
throw std::bad_cast("Lexical cast error");
std::istringstream iss(oss.str());
To to;
iss >> to;
if (!(iss && iss.get() == std::char_traits<char>::eof()))
throw std::bad_cast("Lexical cast error");
return to;
}
int main(int argc, char* argv[])
{
try {
int i = LexicalCast<int>(argc == 1 ? "1234" : argv[1]);
std::cout << i << std::endl;
}
catch (std::bad_cast const& ex) {
std::cerr<< ex.what() << std::endl;
}
}
if you don't like stringstream way
you can do some extra check (like using strspn), then do the casting
--
Thanks
Barry