【问题标题】:How to fix Segmentation fault in a command line argument如何修复命令行参数中的分段错误
【发布时间】:2020-06-03 15:27:45
【问题描述】:

我正在尝试用 C 创建一个密码编码器,到目前为止我有以下代码。 if 语句无法正常工作,并在输入任何内容时弹出分段错误,无论是数字还是字母。应该打印出如何使用密文的else语句只有在有空格时才打印出来。

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <math.h>


int main(int argc, string argv[]) //im certain the problem is on this line but I dont know where exactly nor do I know how to fix it
{
    if (isdigit(argv[1]))
    {
        string s = get_string("Cipher Text: ");
    }
    else
    {
        printf("Usage: ./caesar key\n");
    }
}

我确定错误必须处理命令行参数中的字符串,但我不确定要采取哪些步骤来修复它。

【问题讨论】:

  • 请启用完整的编译器警告,该警告应标记 isdigit(argv[1]) 以传递错误的类型。 CS50 的自制类型string 对您没有任何帮助,它导致的问题比解决的问题多。另外请始终在访问argv之前检查argc

标签: c cs50


【解决方案1】:

这是一个非常小的程序,用于展示如何访问 C 程序的参数。

它只使用标准 C 特性(不是 CS50 或特殊字符串类型)。

#include <stdio.h>



int main(int argc, char **argv) 
{

    int i;

    printf("argc=%d\n", argc);

    for (i=0; i < argc; i++)
        printf("argv[%d]=%s\n", i, argv[i]);

    return 0;
}

【讨论】:

  • 除了stdio.h,其他包括什么?
  • 你是对的:它们是不需要的。我已经删除了它们。
猜你喜欢
  • 2014-03-22
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 2020-09-03
相关资源
最近更新 更多