I've got this code written in C that makes a decimal to binary conversion.
How can I make it that it gets the parameter from the command line in linux?
I know i have to use something like int main(int argc, char *argv[])
but i dont know how to implement it.
#include <stdio.h>
int main()
{
int a[10], decimal, i, j;
printf("\nIntroduceti numarul decimal: ");
scanf("%d", &decimal);
for(i = 0; decimal > 0; i )
{
a[i] = decimal % 2;
decimal = decimal / 2;
}
printf("\nNumarul binar este: ");
for(j = i - 1; j >= 0; j--) {
printf("%d", a[j]);
}
printf("\n");
return 0;
}
CodePudding user response:
You want this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("missing command line argument\n");
return 1;
}
int decimal = (int)strtol(argv[1], NULL, 10);
...
}
- you need a minimal understanding of strings.
- The
(int)
cast is for making clear that we explicitely convert thelong int
returned bystrtol
toint
which may or may not be a smaller type thanlong int
, depending on your platform. - Documentation for
strtol
. - Explanation about
argc
andargv
CodePudding user response:
Answer:
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int a[10], decimal, i, j;
decimal = atoi(argv[1]);
for(i = 0; decimal > 0; i )
{
a[i] = decimal % 2;
decimal = decimal / 2;
}
printf("\nNumarul binar este: ");
for(j = i - 1; j >= 0; j--) {
printf("%d", a[j]);
}
printf("\n");
return 0;
}
Here gcc is the c-compiler, and demo.c is the file name After your file gets successfully compiled then ./a.out is the command to run that build file, and append the command-line argument with it, as shown in the image. atoi(argv1) see argv[0] is the file name, argv1 is the argument, and atoi is used to convert string to int, as we can take only string input from the command line, and argc is the total number of argument user have given.