Parsing Integer to String C

前端 未结 9 1000
情深已故
情深已故 2020-12-14 08:58

How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?

9条回答
  •  余生分开走
    2020-12-14 09:04

    It sounds like you have a string and want to convert it to an integer, judging by the mention of parseInt, though it's not quite clear from the question...

    To do this, use strtol. This function is marginally more complicated than atoi, but in return it provides a clearer indication of error conditions, because it can fill in a pointer (that the caller provides) with the address of the first character that got it confused. The caller can then examine the offending character and decide whether the string was valid or not. atoi, by contrast, just returns 0 if it got lost, which isn't always helpful -- though if you're happy with this behaviour then you might as well use it.

    An example use of strtol follows. The check for error is very simple: if the first unrecognised character wasn't the '\x0' that ends the string, then the string is considered not to contain a valid int.

    int ParseInt(const char *s,int *i)
    {
        char *ep;
        long l;
    
        l=strtol(s,&ep,0);
    
        if(*ep!=0)
            return 0;
    
        *i=(int)l;
        return 1;
     }
    

    This function fills in *i with the integer and returns 1, if the string contained a valid integer. Otherwise, it returns 0.

提交回复
热议问题