C 使用函数getopt的除数数
我正在做一个程序,它接收一个数字,并给出除数的数目。 例如 在cmd中:C 使用函数getopt的除数数,c,string,command-line-arguments,getopt,C,String,Command Line Arguments,Getopt,我正在做一个程序,它接收一个数字,并给出除数的数目。 例如 在cmd中: practica -n 30 预期产出: 1,2,3,5,6,10,15,30 我有以下代码: void divisor(char *temp1); int main(int argc,char **argv){ int option; char *n; while((option =getopt(argc,argv,"n")) !=-1){ switch(option){ case 'n': n=opta
practica -n 30
预期产出:
1,2,3,5,6,10,15,30
我有以下代码:
void divisor(char *temp1);
int main(int argc,char **argv){
int option;
char *n;
while((option =getopt(argc,argv,"n")) !=-1){
switch(option){
case 'n':
n=optarg;
break;
}
}
divisor(n);
}
void divisor(char *temp1){
char f=*temp1;
int n=f-'0';
int a;
a=1;
while (a<n)
{
if(n%a==0)
printf("%d,",a);
a++;
}
a=n;
if(n%a==0)
printf("%d",a);
printf("\b ");
}
我正在使用命令行,程序关闭
我想,你的getopt呼叫应该是
while((option =getopt(argc,argv,"n:")) !=-1){ //notice the :
因为您将为该选项提供一个参数值
也就是说,在你的代码中,在除数函数中
char f=*temp1;
int n=f-'0';
看起来不对。temp是一个字符指针,对指针的解引用只会给出存储的第一个字符的值,预期值30不会存储为单个字符,而是以字典格式存储
我认为,您可以使用将词典表示转换为int值,如
int x = strtol(temp, NULL, 0);
你有没有试着调试你的应用程序,看看它到底出了什么问题?