How to parse a string to an int in C++?

前端 未结 17 1708
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

17条回答
  •  爱一瞬间的悲伤
    2020-11-21 11:59

    I like Dan's answer, esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available.

    Added a check for white-space after a valid string...these three lines

        while (isspace(*end)) {
            end++;
        }
    


    Added a check for parsing errors too.

        if ((errno != 0) || (s == end)) {
            return INCONVERTIBLE;
        }
    


    Here is the complete function..

    #include 
    #include 
    #include 
    #include 
    
    enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
    
    STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
    {
        char *end = (char *)s;
        errno = 0;
    
        l = strtol(s, &end, base);
    
        if ((errno == ERANGE) && (l == LONG_MAX)) {
            return OVERFLOW;
        }
        if ((errno == ERANGE) && (l == LONG_MIN)) {
            return UNDERFLOW;
        }
        if ((errno != 0) || (s == end)) {
            return INCONVERTIBLE;
        }    
        while (isspace((unsigned char)*end)) {
            end++;
        }
    
        if (*s == '\0' || *end != '\0') {
            return INCONVERTIBLE;
        }
    
        return SUCCESS;
    }
    

提交回复
热议问题