gpt4 book ai didi

c - 直接 shell 输入作为 C 程序参数

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:01 25 4
gpt4 key购买 nike

假设我有一个 C 程序,它的函数声明是 void square(int n),(它也被定义了)它所做的一切都是 printf 的平方值 n。我希望能够像这样从 bash shell 运行它:square 5,其中 5 是 C 程序的输入。

我该怎么做?我已经研究过使用 getoptread,我已经多次阅读手册页并观看了一些 getopt 教程,但我可以似乎想出办法做到这一点。我在示例中找不到不使用标志的 getopt 示例,因此我不知道如何将它应用于简单的整数输入。谁能与我分享如何做到这一点?我真的很感激。

最佳答案

如果您没有任何其他需要处理的命令行选项,getopt 可能就太过分了。您只需要从 argv 中读取值:

int main(int argc, char *argv[])
{
int n;

// need "2 args" because the program's name counts as 1
if (argc != 2)
{
fprintf(stderr, "usage: square <n>\n");
return -1;
}

// convert the first argument, argv[1], from string to int;
// see note below about using strtol() instead
n = atoi(argv[1]);

square(n);

return 0;
}

更好的解决方案将 use strtol() instead of atoi()以检查转换是否有效。

关于c - 直接 shell 输入作为 C 程序参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155428/

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