debug assertion failed - argc和argv

时间:2015-11-07 18:32:09

标签: c++ arguments

我尝试编译这个简单的小程序,但是我得到“调试断言失败”,有人可以解释一下原因吗?

#include <stdio.h>
#include <stdlib.h>

#define answer 3.14

void main(int argc, char **argv) 
{
     float a = strtod(argv[1], 0);

     printf("You provided the number %f which is ", a);


     if(a < answer)
          puts("too low");
     else if(a > answer)
          puts("too high");
     else if (a == answer)
          puts("correct");
}

使用方法:

打开CMD并将此.exe拖入其中,然后写一个空格后跟一个数字并按Enter键。例如。 C:\test.exe 240

3 个答案:

答案 0 :(得分:1)

查看这个带有注释的重写代码(根本不是我编译的):

#include <cstdio>    // Include stdio.h  for C++ - see https://msdn.microsoft.com/en-us/library/58dt9f24.aspx
#include <cstdlib>   // Include stdlib.h for C++ - see https://msdn.microsoft.com/en-us/library/cw48dtx0.aspx

#define answer 3.14  // Define value of PI as double value.
                     // With f or F appended, it would be defined as float value.

int main(int argc, char **argv)
{
     if(argc < 2)    // Was the application called without any parameter?
     {
          printf("Please run %s with a floating point number as parameter.\n", argv[0]);
          return 1;
     }

     // Use always double and never float for x86 and x64 processors
     // except you have a really important reason not doing that.
     // See https://msdn.microsoft.com/en-us/library/aa289157.aspx
     // and https://msdn.microsoft.com/en-us/library/aa691146.aspx

     // NULL or nullptr should be used for a null pointer and not 0.
     // See https://msdn.microsoft.com/en-us/library/4ex65770.aspx

     double a = strtod(argv[1], nullptr);

     // %f expects a double!
     printf("You provided the number %f which is ", a);

     // See https://msdn.microsoft.com/en-us/library/c151dt3s.aspx
     if(a < answer)
          puts("too low.\n");
     else if(a > answer)
          puts("too high.\n");
     else
          puts("correct.\n");

     return 0;
}

答案 1 :(得分:0)

我找到了一个可能的解决方案,但我不明白它为什么会起作用。也许有人可以解释为什么argc - 2

float a = (argc -2)? 0 : strtod(argv[1], 0);

答案 2 :(得分:0)

如果我提供至少一个命令行参数,则此代码在我的设置中完美运行。没有任何参数,它会像预期的那样崩溃。