test string for integer

whats the best way to test a string to see if it is an integer?
I can loop through a string and use isdigit(), but that doesn't work if it is a negative number
I tried using atoi, but i get weird results
if I send it the string "1" it returns the integer 1
if I send it the string "-123" it returns the integer -123

but if i send it "123c4", it returns 123. i need that to return an error
if I send it "crft" or any string that doesn't start with a digit, it returns 0.

I just need to check a string, see if it contains an integer, and if so, assign it to an integer var, and if not, dont try to convert, but do some other stuff.
Here is the absolute best way to do it in C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <boost/lexical_cast.hpp>

bool use_int(const std::string& s)
{
    try {
        int var = boost::lexical_cast<int>(s);
        // do stuff with var
    } catch (boost::bad_lexical_cast&) {
        // do other stuff because s is not an int
        return false;
    }
    return true;
}


boost::lexical_cast uses std::stringstream under the covers to do the conversions.
Topic archived. No new replies allowed.