Error checking with strtol()

How do I know whether a return value of 0 from strtol() indicates an error, or simply that the input string was "0"? If string parsing is necessary, this becomes a hassle, so hopefully that's not my only option.

For example, I tried the following, but the return value and errno are the same in each case, so that's no help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main(int argc, char *argv[])
{
    errno = 0;
    int goodValue = strtol("0",NULL,10);
    std::cout << "goodValue: " << goodValue << '\n';
    std::cout << "errno: " << errno << '\n';

    errno = 0;
    int badValue = strtol("zero",NULL,10);
    std::cout << "badValue: " << badValue << '\n';
    std::cout << "errno: " << errno << '\n';
	
    std::cin.get();
    return 0;
}


Output:

goodValue: 0
errno: 0
badValue: 0
errno: 0

strtol return 0 both if input was bad or it was an actual "0".
If you are using C++ you can try stringstreams to perform conversions, so you can check yourself whether it was successful
http://www.cplusplus.com/articles/numb_to_text/
Topic archived. No new replies allowed.