问题描述
- final.exe 文件。
- 这会无限执行或最多执行 50 次。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int i;
if (argc < 2)
{
printf("ERROR: You need at least one argument.\n");
return 1;
}
else
{
int i,j;
for(i=1;i<=(int)*argv[1];i++)
{
printf("\n");
(void)system("test1.exe");
}
}
}
test.c 文件包含:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
printf("Hello World");
}
- 预期 - 例如。 : ./final 2 : 输出应该是 Hello World Hello World ,即只打印 2 次而不是无限打印。
解决方法
(int)*argv[1]
使用第一个字符的字符代码作为迭代次数。字符代码通常从该字符表示的数量不同。
要将字符串转换为对应的数字,可以使用atoi()
(如果您不关心无效输入)。
int i,j;
int num = atoi(argv[1]);
for(i=1;i<=num;i++)
{
printf("\n");
(void)system("test1.exe");
}
,
for(i=1;i<=(int)*argv[1];i++)
表达式 (int)*argv[1]
使用第一个命令行参数(不包括程序名称)的第一个字符作为数字。也就是说,假设是 ASCII-like 或 Unicode-like 编码,字符 0
被视为值 48,1
被视为 49,...,9
被视为 57。{ {1}} 并没有真正的影响。
如果你真的只想使用第一个字符,你可以做类似的事情
(int)
或者要允许多位数计数,您可以执行类似的操作
if (isdigit(*argv[1])) {
int count = *argv[1] - '0'; // works with any encoding