1

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;
}
Zeus
  • 41
  • 6

2 Answers2

3

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 the long int returned by strtol to int which may or may not be a smaller type than long int, depending on your platform.
  • Documentation for strtol.
  • Explanation about argc and argv
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
2

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;
}

Compile Image Open it

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • When I enter the value 2147483647, the largest number, after showing the binary code, linux says `stack smashing detected *** terminated aborted (core dumped)`, can i fix this somehow? – Zeus Mar 17 '22 at 16:52
  • 1
    No, there is the range and your input should be in b/w that range, but 2147483647 is exceeding that, hence resulting in buffer overflow kind of scenario, that's why that error is coming. – NIKHIL KUMAR GUPTA Mar 17 '22 at 17:36