我试图从我代码中的 c 修饰符的 optarg 获取一个 int,但我无法获取它,我试图转换它但这是不可能的,所以我调查并发现这个 atoi() 函数应该从字符串中获取一个 int,但它仍然打印错误“格式‘%d’需要类型为‘int’的参数,但参数 3 的类型为‘int (*)()’”。这是代码(还没完):
if(strcmp(argv[1], "crea") == 0){
if(argc>7 || argc<6){
fprintf(stderr, "Número de argumentos incorrecto, el uso es : ./misala crea -f [nombre archivo] -c [capacidad] [-o]\n");
exit(1);
}
int c;
while((c=getopt(argc, argv, "f:oc:n:a:"))!=-1){
switch (c){
case 'f':
f_flag = 1;
ruta = malloc(sizeof(char)*strlen(optarg));
strcpy(ruta, optarg);
break;
case 'o':
o_flag = 1;
break;
case 'c':
c_flag = 1;
int capacidad;
//here I want to get an int from optarg to store in variable capacidad
capacidad = atoi(optarg);
break;
case '?':
fprintf(stderr, "Modificador no válido");
break;
}
}
//here the error is triggered (only with capacidad, ruta is propertly working)
printf("RUTA = %s, CAPACIDAD = %d\n", ruta, capacidad);
}
}
void main(int argc, char* argv[]){
ejecuta_funcion(argc, argv);
}```
您需要在
int capacidad;
语句可以访问它的范围内定义变量printf()
。更喜欢 atol()
而不是 atoi()
因为后者不支持正确的错误处理。不要对变量和函数使用相同的名称。它们在同一个名称空间中。