【问题标题】:strtod - Problem in converting string to doublestrtod - 将字符串转换为双精度的问题
【发布时间】:2011-07-24 09:59:45
【问题描述】:

我有一个非常小的程序,可以将字符串转换为双精度。问题是每次打印 0.0000。 请帮帮我。

提前致谢。

enter code here

$ export LT_LEAK_START=1.5
$ echo $LT_LEAK_START
  1.5

#include <stdio.h>

int main()
{
  double d;
  d=strtod(getenv("LT_LEAK_START"), NULL);
  printf("d = %lf\n",d);
}
Output:
d=0.0000000

【问题讨论】:

  • @Raveline:谢谢 Raveline。很有用。

标签: c char double strtod


【解决方案1】:

尝试包括

#include <stdlib.h>

【讨论】:

  • @codaddict:如果strtod需要stdlib.h,那么为什么编译时不会出错?如何在 C++ 中使用它? #include 会起作用吗?
  • @kingsmasher1:你编译时没有警告。对于 gcc,请使用 -Wall。对于 c++ #include &lt;cstdlib&gt;
  • @Erik:我猜,如果没有-Wall,gcc 也会对不兼容的类型转换等发出警告。不是吗?那为什么要-Wall 这个案例呢?
  • @kingsmasher1:使用未声明的函数不是语言错误。它只是具有有趣的效果,例如假设一个函数在未声明的情况下返回 int。您应该始终使用-Wall 进行编译,它会捕获很多常见错误。
  • @Erik:谢谢,这很有用。
【解决方案2】:

您没有包含 strtod decl 标头 (stdlib.h),因此您使用的是内部 strtod 实现(这似乎只是一个存根?)

root@pinkpony:~# gcc -Wall -g  -o t t.c
t.c: In function ‘main’:
t.c:6: warning: implicit declaration of function ‘strtod’
t.c:6: warning: implicit declaration of function ‘getenv’
t.c:8: warning: control reaches end of non-void function
root@pinkpony:~# gdb ./t
Reading symbols from /root/t...done.
(gdb) run
Starting program: /root/t 

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a96b64 in ____strtod_l_internal (nptr=<value optimized out>, endptr=<value optimized out>, group=<value optimized out>, loc=0x7ffff7dd6580) at strtod_l.c:530
5    30     strtod_l.c: No such file or directory.
        in strtod_l.c
(gdb) bt
#0  0x00007ffff7a96b64 in ____strtod_l_internal (nptr=<value optimized out>, endptr=<value optimized out>, group=<value optimized out>, loc=0x7ffff7dd6580) at strtod_l.c:530
#1  0x00000000004005bc in main () at t.c:6
(gdb) 

忽略 sigsegv,在我的平台上是由 getenv() 引起的,它也在 stdlib 中声明,但没有内部 gcc impl

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多