gpt4 book ai didi

c - c 中 main 的程序参数 - ./dev --print

转载 作者:行者123 更新时间:2023-11-30 15:03:03 25 4
gpt4 key购买 nike

我正在尝试让程序检查用户在运行程序时是否传递程序参数。效果:

./dev --print

我想出了以下内容:

int main(int argc, char *argv[]) {
char print[] = "--print";
if(strcmp(argv[1], print) == 0) {
solve_a_bunch_of_functions_and_print_without_user_input();
}
else {
ask_for_user_input();
then_solve_bunch_of_functions();
}
}

这是正确/最明智的方法吗?

目前,每次我进入 else 语句时,我都会遇到此实现后的段错误问题。不确定我在这里的实现与它有什么关系。

最佳答案

是的,这是一种方法,尽管我认为大多数 C 程序员不会为单独的变量而烦恼,而只是这样做:

if(strcmp(argv[1], "--print") == 0)

当然,您应该首先通过检查 argc 来验证 argv[1] 中是否有参数。否则,您会将 NULL 传递给 strcmp(),这是一个坏主意。

if(argc > 1 && strcmp(argv[1], "--print") == 0)
{
}

关于c - c 中 main 的程序参数 - ./dev --print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40865154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com