Detecting if a string is a double or long in C

拜拜、爱过 提交于 2019-12-13 04:29:15

问题


I'm dealing with an char[] containing text which should represent a double number value OR a long number.
I'm in a need to write a function that detects which of the above data-types is represented (if any).

I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod().

I would be happy to see whether there is a better option to do so. Thanks.


回答1:


I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod().

I think that's a good idea and I don't think there is a better one. Implementing your own parsing routine is generally a bad idea.

I would trim the string from trailing whitespace before calling strtol to avoid false negatives.




回答2:


strtol() and strtod() is the right approach. Be sure to use errno to detect integer overflow. 2 stand-alone functions follow:

int  Is_long(const char *src, long *dest) {
  char *endptr;
  // Clear, so it may be tested after strtol().
  errno = 0;  
  // Using 0 here allows 0x1234, octal 0123 and decimal 1234. 
  long num = strtol(src, &endptr, 0);
  // If +/- overflow, "" or has trailing text ...
  if (errno || endptr == src || *endptr != '\0') {
    return 0;
  }
  if (dest) *dest = num;
  return 1;
}

int  Is_double(const char *src, double *dest) {
  char *endptr;
  // In this case, detecting over/undeflow IMO is not a concern, so ignore it.
  double num = strtod(src, &endptr);
  // If "" or has trailing text ...
  if (endptr == src || *endptr != '\0') {
    return 0;
  }
  if (dest) *dest = num;
  return 1;
}

@Klas Lindbäck does bring up the good point of what to do about trailing white-space. This answer assumes it is not valid.




回答3:


 You can use the following code to detect that.

 char* isDouble = strchr(string, '.');
 if (isDouble) { 
   // is Double here
 }else {
   // is long here
 }


来源:https://stackoverflow.com/questions/21696242/detecting-if-a-string-is-a-double-or-long-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!