How to portably convert a string into an uncommon integer type?

前端 未结 3 884
臣服心动
臣服心动 2020-12-30 07:46

Some background: If I wanted to use for, for instance, scanf() to convert a string into a standard integer type, like uint16_t, I’d use SCNu1

3条回答
  •  北海茫月
    2020-12-30 08:23

    There is one robust and portable solution, which is to use strtoimax() and check for overflows.

    That is, I parse an intmax_t, check for an error from strtoimax(), and then also see if it "fits" in a pid_t by casting it and comparing it to the original intmax_t value.

    #include 
    #include 
    #include 
    #include 
    char *xs = "17";            /* The string to convert */
    intmax_t xmax;
    char *tmp;
    pid_t x;                    /* Target variable */
    
    errno = 0;
    xmax = strtoimax(xs, &tmp, 10);
    if(errno != 0 or tmp == xs or *tmp != '\0'
       or xmax != (pid_t)xmax){
      fprintf(stderr, "Bad PID!\n");
    } else {
      x = (pid_t)xmax;
      ...
    }
    

    It is not possible to use scanf(), because, (as I said in a comment) scanf() will not detect overflows. But I was wrong in saying that none of the strtoll()-related functions takes an intmax_t; strtoimax() does!

    It also will not work to use anything else than strtoimax() unless you know the size of your integer type (pid_t, in this case).

提交回复
热议问题