c中的一个简单的strtod()示例

时间:2022-11-04 19:57:31

When I read strtod() example , I have some doubt. Here is the code:

当我读到strtod()示例时,我有一些疑问。这是代码:

const char *p = "111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz";
printf("Parsing '%s':\n", p);
char *end;
double f; 
for (f = strtod(p, &end); p != end; f = strtod(p, &end))
{
    printf("'%.*s' -> ", (int)(end-p), p);//I can't understand this line
    p = end;
    if (errno == ERANGE){
        printf("range error, got ");
        errno = 0;
    }
    printf("%f\n", f);
}

Output:

Parsing '111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz':
'111.11' -> 111.110000
' -2.22' -> -2.220000
' Nan' -> 1.#QNAN0
' nan(2)' -> 1.#SNAN0
' inF' -> 1.#INF00
' 0X1.BC70A3D70A3D7P+6' -> 111.110000
'  1.18973e+4932' -> range error, got 1.#INF00

Why can end - p get a value?

为什么可以结束-p获得价值?

1 个解决方案

#1


3  

strtod(p, &end) sets end to point to the next byte after the number that was parsed. So when you make this call with the initial string, the result is:

strtod(p,&end)设置end to指向解析后的数字后面的下一个字节。因此,当您使用初始字符串进行此调用时,结果为:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
^     ^
p    end

end-p is then the length of the number that was parsed. When you write

end-p则是解析后的数字的长度。当你写作

printf("'%.*s' -> ", (int)(end-p), p);

this length is used for the .* size of the %s field, which makes it only print that many bytes of the string.

此长度用于%s字段的。*大小,这使得它只打印字符串的许多字节。

The loop then sets p = end and repeats, so this time you get:

然后循环设置p = end并重复,所以这次你得到:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
      ^     ^
      p    end

The loop keeps doing this to find each number in the string. If it can't parse a number at the location in the string, it sets end to point to the input string, and the test p != end fails, so the loop ends.

循环继续这样做以查找字符串中的每个数字。如果它无法解析字符串中某个位置的数字,则它会端到端地设置输入字符串,并且测试p!= end失败,因此循环结束。

#1


3  

strtod(p, &end) sets end to point to the next byte after the number that was parsed. So when you make this call with the initial string, the result is:

strtod(p,&end)设置end to指向解析后的数字后面的下一个字节。因此,当您使用初始字符串进行此调用时,结果为:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
^     ^
p    end

end-p is then the length of the number that was parsed. When you write

end-p则是解析后的数字的长度。当你写作

printf("'%.*s' -> ", (int)(end-p), p);

this length is used for the .* size of the %s field, which makes it only print that many bytes of the string.

此长度用于%s字段的。*大小,这使得它只打印字符串的许多字节。

The loop then sets p = end and repeats, so this time you get:

然后循环设置p = end并重复,所以这次你得到:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
      ^     ^
      p    end

The loop keeps doing this to find each number in the string. If it can't parse a number at the location in the string, it sets end to point to the input string, and the test p != end fails, so the loop ends.

循环继续这样做以查找字符串中的每个数字。如果它无法解析字符串中某个位置的数字,则它会端到端地设置输入字符串,并且测试p!= end失败,因此循环结束。