IF YOU ARE USING C++11, YOU CAN USE THE FOLLOWING:
It appears this snippet of code is okay: can you please post a large block of code or the entire file so that we may inspect it? The answer may not always be where you are looking for it.
On another note, why not use boost::lexical_cast? If you're not feeling up to it, I have a copy of a non-boost lexical_cast function here that works just as it is:
#include <iostream>
#include <string>
#include <sstream>
#include <typeinfo>
template <typename T>
T lexical_cast(const std::string& s)
{
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast();
}
return result;
}
Notice how this form of the function uses std::stringstream as well, so why just use it alone? The good thing about this is that it is usable for more than just int, as, being a template, it can also accommodate other types of data. Note that I only tested this with int and float.
Note: if you decide to use this *template version of lexical_cast* and put it in a separate file, you will end up having to declare it within the header file.
To call lexical_cast with an int:
int whatever = lexical_cast <int>(stringOfYourChoice);