【问题标题】:C Commandline Arguments: Need Clarification About Order of Arguments Input And Commandline Arguments In GeneralC 命令行参数:需要澄清关于参数输入顺序和命令行参数的一般情况
【发布时间】:2021-01-12 11:43:04
【问题描述】:

这是一本书的示例代码。该程序打印给定的字符串以重复给定的次数。

#include <stdio.h>
#include <stdlib.h>

void usage(char *program_name)
{
    printf("Usage: %s <nessage> <# of times to repeat>\n", program_name);
    exit(1);
}

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

    if(argc < 3)
        usage(argv[0]);

    count = atoi(argv[2]);
    printf("Repeating %d times..\n", count);

    for(i=0; i < count; i++)
       printf("%3d - %s\n", i, argv[1]);
}

它做了它应该做的:

kingvon@KingVon:~/Desktop/asm$ ./convert 'Stackoverflow is the best place to ask questions about programming' 6
Repeating 6 times..
  0 - Stackoverflow is the best place to ask questions about programming
  1 - Stackoverflow is the best place to ask questions about programming
  2 - Stackoverflow is the best place to ask questions about programming
  3 - Stackoverflow is the best place to ask questions about programming
  4 - Stackoverflow is the best place to ask questions about programming
  5 - Stackoverflow is the best place to ask questions about programming
kingvon@KingVon:~/Desktop/asm$ 

问。现在虽然main 以这个特定的顺序接受两个参数:(int argc, char *argv[]),但为什么当我./convert 'string' (number) 时它可以正常工作,但 `./convert (number) 'string' 的其他方式不起作用?

kingvon@KingVon:~/Desktop/asm$ ./convert 5 'Stackoverflow is the best place to ask questions about programming'
Repeating 0 times..

问。这条线 if(argc &lt; 3) usage(argv[0]); 我有 2 个问题: 此行指定如果给定的整数参数小于 3,则程序应输出用法。 ./convert 'string' 2 不打印用法?那么这里发生了什么?同样usage 将char *program_name 作为参数(char *program_name 是什么意思?)但在上面的行中给出了argv[0] 作为参数。为什么会这样?这样做有什么作用?

【问题讨论】:

  • 当你做./convert 'Stackoverflow is the best place to ask questions about programming' 6时,argc不是6。
  • 为什么投反对票?

标签: c command-line-arguments


【解决方案1】:

argc 是命令行上的参数数量,而不是任何特定参数的值。 argv 包含实际参数,它们作为字符串传递。 argv[0] 是用来调用程序的命令,argv[1] 是第一个参数,等等

当你调用程序时

./convert 'Stackoverflow ...' 6

然后

argv[0] == "./convert"
argv[1] == "Stackoverflow ..."
argv[2] == "6”
argc == 3

代码假定数字是在argv[2] 中传递的,并使用atoi 函数将其从整数的字符串表示形式转换为整数值,这就是为什么当您使用切换了参数的顺序。如果您希望能够切换参数的顺序,那么您的代码必须知道如何检测哪个参数是哪个。

【讨论】:

  • 好的。我正在阅读的这本书希望我在阅读这本书之前就知道这一点。
  • @raincouver:是的,大多数 C 书籍和教程都......不是很好。
【解决方案2】:

argc 变量是argv 数组中的元素数。而实际的命令行参数将在argv 数组中。

命令行的第一个参数总是在argv[1],第二个在argv[2],等等。

如果你在运行程序的时候改变了顺序,程序并不知道这一点,并且会认为要打印的字符串仍然在argv[1]和argv[2]中的数字。如果不是这样,程序将无法正常运行。

argc 检查只检查参数的个数,而不是它们的顺序。


程序的名称(您的问题中的"./convert" )始终作为参数零传递,即在argv[0] 中。

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2014-02-19
    • 2012-10-22
    • 2020-07-31
    • 2012-10-04
    • 2016-02-24
    • 1970-01-01
    • 2017-06-26
    • 2016-12-22
    相关资源
    最近更新 更多