我希望 endptr
指向与 strtod()
和 strtold()
相同的值。然而他们不同。我怀疑 strtold()
不正确。 OTOH,这可能是规范不明确且任一结果都可以接受的情况。
这是一个错误(以及哪个函数)或未定义/未指定的行为?
使用:gcc\x86_64-pc-cygwin\4.8.3
#include <math.h>
#include <stdio.h>
// Edit - This include is in my true code, but was missing in original post
#include <stdlib.h>
int main(void) {
char *s = "123ez";
char *endptr;
double d = strtod(s, &endptr);
printf(" double %f '%s'\n", d, endptr);
long double ld = strtold(s, &endptr);
printf("long double %Lf '%s'\n", ld, endptr);
return 0;
}
Output:
double 123.000000 'ez'
long double 123.000000 'z'
[编辑]
gcc 命令 gcc -I"C:\cygwin64\lib\gcc\x86_64-pc-cygwin\4.8.3\include"-O0 -g3 -Wall -c -fmessage-length=0 -std= c99 -MMD -MP -MF"string_fp.d"-MT"string_fp.d"-o "string_fp.o""../string_fp.c"
海湾合作委员会 4.9.2
最佳答案
两者都不应该使用 e
。要允许使用 e
,e
之后必须有一个非空的数字序列。 GCC 4.9.0 与 Glibc 2.12 的行为正确。
[2:29pm][wlynch@apple /tmp] ./a.out
double 123.000000 'ez'
long double 123.000000 'ez'
引用 C 2011 标准草案 N1570 中的内容...
Section 7.22.1.3 Paragraph 3: The strtod, strtof, and strtold functions
The expected form of the subject sequence is an optional plus or minus sign, then one of the following:
- a nonempty sequence of decimal digits optionally containing a decimal-point character, then an optional exponent part as defined in 6.4.4.2;
- ...
Section 6.4.4.2 Floating Constants
exponent-part: e signopt digit-sequence E signopt digit-sequence digit-sequence: digit digit-sequence digit
我认为这是您正在运行的 C 标准库中的错误。
关于c - 带有 strtod()/strtold() 的意外 endptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29040427/