Search code examples
c++stringinteger

How to convert a string to int and handle invalid strings with non-digit characters


Hello I know it was asked many times but I hadn't found answer to my specific question.

I want to convert only string that contains only decimal numbers:

For example 256 is OK but 256a is not.

Could it be done without checking the string?

Thanks


Solution

  • The simplest way that makes error checking optional that I can think of is this:

    char *endptr;
    int x = strtol(str, &endptr, 0);
    int error = (*endptr != '\0');