【问题标题】:segmentation fault using scanf to read doubles使用 scanf 读取双精度的分段错误
【发布时间】:2013-12-18 12:11:27
【问题描述】:

我正在为作业编写输入部分,如果命令行输入是一个它应该接受键盘输入 - 其中一个输入不起作用。

这是我遇到问题的代码段。如果行 scanf("%lf %lf", &r1, &r2);不理会它会产生分段错误-如果将其更改为写入另一个变量,则一切正常。我很难理解为什么是那个变量导致了问题,它实际上是从上面的行粘贴的,我将四个字符从 k 更改为 r 并且这两个变量在同一行中声明!请尽快提供帮助,在解决此问题之前,我无能为力。我已经尝试将变量名称更改为 l1 和 l2,但是当功能障碍线与功能线如此相似时,我想不出还有什么可做的

    double  time[10000], x1[10000], x2[10000], v1[10000], v2[10000];
double  m1, m2, k1, k2, r1, r2, w1, w2;
int     count, inmethod;

time[0] = 0;
x1[0] = 0;  x2[0] = 10;
v1[0] = 0;  v2[0] = 0;
m1 = 5;     m2 = 5;
k1 = 5;     k2 = 5;
r1 = 5;     r2 = 10;
w1 = 0;     w2 = 0;

sscanf(argv[1], "%d", &inmethod);
//  printf("%d \n", inmethod);


if((argc == 2) && ((inmethod == 1) || (inmethod == 0)))
{
}

else
{
    printf("enter 1 for file input or 0 to enter input via the keyboard. you will be able to save your input for future use.\n");
    return(EXIT_FAILURE);
}

if(inmethod == 1)
{
    printf("system properties: \n");

    printf("please enter m1 then m2, seperated by a space and followed by enter\n");
    scanf("%lf %lf", &m1, &m2);

    printf("please enter k1 then k2, seperated by a space and followed by enter \n");
    scanf("%lf %lf", &k1, &k2);

    printf("please enter r1 then r2, seperated by a space and followed by enter \n");
    scanf("%lf %lf", &r1, &r2);

    printf("please enter w1 then w2, seperated by a space and followed by enter \n");
    scanf("%lf %lf", &w1, &w2);

    printf("initial conditions: \n");

    printf("please enter x1[0] then x2[0], seperated by a space and followed by enter \n");
    scanf("%lf %lf", &x1[0], &x2[0]);

    printf("please enter v1[0] then v2[0], seperated by a space and followed by enter \n");
    scanf("%lf %lf", &v1[0], &v2[0]);

}

【问题讨论】:

  • 如果您想将字符串转换为数字,就像使用argv[1] 一样,那么您可能需要使用strtol。您可能还想检查argc之前这样做。
  • 为我工作。除第一个参数外,所有输入都是双精度的。你在混吗。并且,在输入浮点数时?
  • 对于这些情况,scanf 可能是最好的选择(当然有strtod)。我的意思是,当您将 argv[1] 转换为整数时,sscanf 可能不是最好的。
  • 当我将您的代码复制并粘贴到我的机器上时,它编译得很好......只是添加了一个 main 来运行。你能举例说明你的输入吗?
  • 拼写提示:SEPARATE 中有 A RAT。并且不检查 scanf 的返回值是在要求灾难。

标签: c segmentation-fault scanf


【解决方案1】:

您的代码看起来不错。它为我编译并且工作正常。

请检查您的输入值。 scanf 对于输入验证确实很弱,您需要检查函数返回并为更糟的情况做好准备。如果你需要接受这样的键盘输入,尝试使用 gnu readline 或者输入功能更好的库。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2019-06-20
    • 1970-01-01
    • 2015-06-15
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多