c - 使用 argv[] 时我的代码不接受命令行参数

标签 c argv cs50 caesar-cipher

我正在尝试将命令行参数转换为变量(第 17 行,“key”)。当我运行程序时除了命令行中的名称外没有其他任何东西 (例如 $ ./caesar)我没有收到任何错误,但代码没有超过下面显示的行。但是,当我使用任何命令行参数(例如 $ ./caesar 2)运行程序时,代码会给出如下所示的错误。

我必须使用 argv 作为键,因为这是此作业中的要求(如果有帮助,我正在为 CS50 这样做)。我不知道 argv 是如何工作的,对它的研究对我没有帮助。因此,我没有尝试太多有助于调试的方法。链接到 cs50 库:https://cs50.readthedocs.io/library/c/

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

int main(int argc, string argv[]){
    if (argc != 2){ //limits args code will accept to one
        return 1;
    }
    if (isdigit(argv[1]) == true){ //checks if first arg is digit
        printf("Usage: ./caesar key\n");
        return 1;
    } else {
        printf("Success\n");
    }

    int key = atoi(argv[1]); // converting first arg to int

这是我在使用任何命令行 arg 时遇到的错误,以及我如何编译程序。

$ make caesar
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    caesar.c  -lcrypt -lcs50 -lm -o caesar
$ ./caesar 2
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1070==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x7f259d8849b2 (pc 0x0000004281c1 bp 0x7fff67ba6ad0 sp 0x7fff67ba68f0 T1070)
==1070==The signal is caused by a READ memory access.
    #0 0x4281c0 in main /root/sandbox/caesar.c:10:9
    #1 0x7f24cdfb6b96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310
    #2 0x402b89 in _start (/root/sandbox/caesar+0x402b89)

UndefinedBehaviorSanitizer can not provide additional info.
==1070==ABORTING

最佳答案

sscanf 可用于扫描 argv[1] 中的整数。
sscanf 将返回成功扫描的项目数。

#include <stdio.h>

int main ( int argc, char *argv[]) {
    int key = 0;
    if (argc != 2){ //limits args code will accept to one
        printf("Usage: ./%s key\n", argv[0]);
        return 1;
    }
    if ( 1 != ( sscanf ( argv[1], "%d", &key))) { //try to scan an int
        printf("Usage: ./%s key\n", argv[0]);
        return 1;
    } else {
        printf("Success\n");
    }
    return 0;
}

正如 @NeilEdelman 所建议的那样,代码可以压缩为

#include <stdio.h>

int main ( int argc, char *argv[]) {
    int key = 0;
    if ( argc != 2 || 1 != ( sscanf ( argv[1], "%d", &key))) { //try to scan an int
        printf("Usage: ./%s key\n", argv[0]);
        return 1;
    } else {
        printf("Success\n");
    }
    return 0;
}

关于c - 使用 argv[] 时我的代码不接受命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137012/

相关文章:

C 中枚举成员的正确用法

C - 我可以将 char *argv[](命令行参数)表示为结构变量的字符数组吗?

c++ - 我可以使用 std::string* argv 作为主函数参数吗?

c - cs50 Segfau 中的维吉尼亚密码

c - ASM 调用约定

c - 如何遍历由指针创建的字符串

凯撒密码输出空行

c - 如何获取 'isalpha' 遍历字符串的每个字符?

c - 如何 malloc modbus_t

python - 对于 sys.argv[1 :]: argument list too long 中的 fi