检测字符串是否为C中的double或long
我正在处理包含文本的char [],该文本应表示双数值或长数字。
我需要编写一个函数来检测上述哪些数据类型(如果有的话)。
我想过使用strtol()并检查它是否无法解析整个字符串,如果失败,则使用strtod()。
我很高兴看到有更好的选择。 谢谢。
我想过使用strtol()并检查它是否无法解析整个字符串,如果失败,则使用strtod()。
我认为这是一个好主意,我不认为有更好的想法。 实现自己的解析例程通常是个坏主意。
我会在调用strtol
之前修剪尾随空格的字符串,以避免误报。
strtol()
和strtod()
是正确的方法。 一定要使用errno
来检测整数溢出。 2个独立function如下:
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; }
@KlasLindbäck确实提出了如何处理白色空间的好处。 这个答案假定它无效。
You can use the following code to detect that. char* isDouble = strchr(string, '.'); if (isDouble) { // is Double here }else { // is long here }