细分错误:命令参数(argv) [英] Segmentation Error : Command Arguments (argv)

查看:71
本文介绍了细分错误:命令参数(argv)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
  if (argc == 2)
  {
    printf ("%s \n", argv[1]);
    
    if (isdigit (argv[1]) !=0)
     {
        printf("Success\n");
        printf("%s \n", argv[1]);
     }
    else
     {
        printf(" %s key \n", argv[0]);
     }
  }
     else
     {
        printf(" %s key \n", argv[0]);
     }

}

大家好,我正在尝试运行该程序接受命令行参数并检查它们的数字,之后我必须将其存储到变量中。我被卡住了,它给出了错误分段错误。我用谷歌搜索它,我认为这意味着该程序无法读取该值。请让我知道为什么会产生错误,什么是细分错误?

Hello everyone, I am trying to run this program that takes command line arguments and checks them for digits.After that I have to store it into a variable. I am stuck and it is giving the error "Segmentation fault". I googled it and I think it means that the program is not able to read the value. Please let me know why it is giving the error, what "Segmentation fault" means and how to fix it.

推荐答案

我相信问题出在

 isdigit (argv[1])

argv [1] 的类型为 char * ,但 isdigit() 期望 int

如果要检查提供的参数是否为全数字值,则必须

If you want to check whether the supplied argument is all-numerical value or not, you have to either


  • 将<$ c中的元素$ c> argv [n] 并将它们一一传递给 isdigit()支票。

  • 使用 strtol() 或类似于检查有效性。

  • Loop over the elements in argv[n] and pass them one by one to isdigit() check.
  • use strtol() or similar to check for the validity.

这篇关于细分错误:命令参数(argv)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆