I'm doing a program which receives a number and gives you the number of divisors. e.g. in the cmd :
practica -n 30
Expected output:
1,2,3,5,6,10,15,30
I have this code:
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 ");
}
I'm using the command line and the program closes.
I think, your getopt()
call should look like
while((option =getopt(argc,argv,"n:")) !=-1){ //notice the :
as you'll be supplying an argument (value) for that option.
That said, in your code, inside divisor()
function,
char f=*temp1;
int n=f-'0';
looks wrong. temp
is a char
pointer an dereferencing the pointer only gives you the value of the first char
stored, and the expected value , 30
is not stored as a single char
, rather it's stored as lexicographical format.
I think, you can use strtol()
to convert the lexicographical representation to int
value, like
int x = strtol(temp, NULL, 0);