在 C 中检查命令行参数是否有错误
Checking Command Line arguments for error in C
我正在尝试检查参数计数,如果命令行中没有参数或超过 2 个参数,应该 return 1
:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
for (int i = 0; i < n; i++) //validating the key array
{
if (n != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else if (!isalpha(key[i]))
{
printf("Key must contain only alphabetic character.\n");
return 1;
}
for (int j = i + 1; j < n; j++)
{
if (key[i] == key[j])
{
printf("Key must not contain repeated characters.\n");
return 1;
}
}
}
}
当我 运行 没有参数时它会抛出一个错误:
runtime error: null pointer passed as argument 1, which is declared to never be null
Segmentation fault (core dumped).
如果我在评论密钥验证部分,它会运行。
我是 C 编程 的新手,并且在谷歌上搜索了很多。
请帮我看看为什么?
您首先访问 argv[1]
,它可能不存在,然后您检查 argc
以查看它是否存在。这是错误的顺序。首先检查 argc
,然后访问 argv[1]
:
int main(int argc, char *argv[])
{
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
// remaining code...
我正在尝试检查参数计数,如果命令行中没有参数或超过 2 个参数,应该 return 1
:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
for (int i = 0; i < n; i++) //validating the key array
{
if (n != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else if (!isalpha(key[i]))
{
printf("Key must contain only alphabetic character.\n");
return 1;
}
for (int j = i + 1; j < n; j++)
{
if (key[i] == key[j])
{
printf("Key must not contain repeated characters.\n");
return 1;
}
}
}
}
当我 运行 没有参数时它会抛出一个错误:
runtime error: null pointer passed as argument 1, which is declared to never be null Segmentation fault (core dumped).
如果我在评论密钥验证部分,它会运行。 我是 C 编程 的新手,并且在谷歌上搜索了很多。 请帮我看看为什么?
您首先访问 argv[1]
,它可能不存在,然后您检查 argc
以查看它是否存在。这是错误的顺序。首先检查 argc
,然后访问 argv[1]
:
int main(int argc, char *argv[])
{
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
// remaining code...