大佬教程收集整理的这篇文章主要介绍了C 命令行参数:需要澄清参数输入的顺序和一般的命令行参数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一本书中的示例代码。该程序打印给定的字符串以重复给定的次数。
#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$
问。现在虽然 @H_229_5@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 < 3) usage(argv[0]);
我有 2 个问题:这一行指定如果给定的整数参数小于 3,则程序应输出用法。 ./convert 'String' 2
不打印用法?那么这里发生了什么?同样 usage
将 char *program_name
作为参数(char *program_name
是什么意思?)但是在上面的行中给出了 argv[0]
作为参数。这是为什么,这是做什么的?
argc
是命令行上的参数数量,而不是任何特定参数的值。 argv
包含作为字符串传递的实际参数。 argv[0]
是用于调用程序的命令,argv[1]
是第一个参数等。
当你调用程序时
./convert 'Stackoverflow ...' 6
然后
argv[0] == "./convert"
argv[1] == "Stackoverflow ..."
argv[2] == "6”
argc == 3
代码假定数字在 argv[2]
中传递并使用 atoi
函数将其从整数的字符串表示形式转换为整数值,这就是代码没有表现的原因当您切换参数的顺序时,正如预期的那样。如果您希望能够切换参数的顺序,那么您的代码必须知道如何检测哪个参数是哪个。
argc
变量是 argv
数组中的元素数。实际的命令行参数将在 argv
数组中。
命令行上的第一个参数总是在 argv[1]
中,第二个在 argv[2]
中,以此类推。
如果你在运行程序时改变了顺序,程序并不知道这一点,并且会认为要打印的字符串仍然在argv[1]
中,而数字在argv[2]
中。如果不是这样,程序将无法正常工作。
argc
检查只检查参数的数量,而不是它们的顺序。
程序名称(您的问题中的 "./convert"
)始终作为参数零传递,即在 argv[0]
中。
以上是大佬教程为你收集整理的C 命令行参数:需要澄清参数输入的顺序和一般的命令行参数全部内容,希望文章能够帮你解决C 命令行参数:需要澄清参数输入的顺序和一般的命令行参数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。