首页 文章

C:带字符串的命令行参数

提问于
浏览
0

我正在尝试编写一个程序,它将一个字符串作为命令行参数,然后通过一个以字符串作为输入的函数(str_to_int)运行所述参数 . 但是,当我尝试编译程序时,我收到警告说

initializing 'char *' with an expression of type 'int' [-Wint
conversion]
  char* str = atoi(argv[1]);
    ^     ~~~~~~~~~~~~~

当我运行程序时出现分段错误,我已经对str_to_int进行了很多测试,所以我很确定问题在于命令行程序 . 这是它的代码 .

#include "hw3.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[])
{
  char* str = atoi(argv[1]);
  printf("%d\n", str_to_int(str));
  return 0;
}

谁能告诉我我做错了什么?谢谢 .

3 回答

  • 0

    这就是您所需要的,但如果省略命令行参数,它将崩溃 .

    {
        printf("%d\n", str_to_int(argv[1]));
        return 0;
    }
    

    这更加强大:

    int main(int argc, char *argv[])
    {
        if (argc == 1)
            printf("missing parameter.");
        else
            printf("%d\n", str_to_int(argv[1]));
    
        return 0;
    }
    
  • 0
    #include "hw3.h"
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int main(int argc, char *argv[])
    {
      char* str = argv[1];
      printf("%d\n", str_to_int(str));
      return 0;
    }
    
  • 0

    只需删除 atoi 函数调用,它应该工作

相关问题