Home > OS >  Reading from command prompt
Reading from command prompt

Time:01-03

I'm just trying to fetch the input from command prompt and want to convert the input to integer.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)    
{   
    int num;
    if(atoi(argv)==0) 
    {
        printf("Enter the number : ");
        scanf("%d",&num);
    }
    else
    {
        num = atoi(argv);
    }
}

Above is what I've tried, and I don't know where I've went wrong.

enter image description here

For the below code I'm getting the error as showed in the picture. I want to run it in both the way like getting from the command prompt and if there is no input from command prompt the values must be fetched when the program runs.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)    
{   
    int num_of_values,sum = 0;
    int i;
    float avg;
    if(atoi(argv[1])==0) 
    {
        printf("Enter the number of values: ");
        scanf("%d",&num_of_values);
        int* sum_arr = malloc(num_of_values*sizeof(int));
        printf("Enter the values: ");
        for(i=0;i<num_of_values;i  )
        {
            scanf("%d",&sum_arr[i]);
            sum =sum_arr[i];
        } 
    }
    else
    {
         for (i = 2; i<=argc; i  ) {
            sum =atoi(argv[i-1]);
         }
         num_of_values = i-2;
    }
    avg = sum / num_of_values;
    printf("Sum and Average is %d and %f", sum,avg);
    
   
}

CodePudding user response:

  • In if(atoi(argv)==0) you probably want to check how many arguments the user gave at the command line. That's what argc is for.
  • num = atoi(argv); should be num = atoi(argv[1]);
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    int num;
    
    if (argc < 2) {                          // no argument given on cmdline
        printf("Enter the number : ");
        if (scanf("%d", &num) != 1) {        // check that scanf succeeds
            puts("Failed reading a number");
            return 1;
        }
    } else {
        num = atoi(argv[1]);                 // dereferencing the second element
    }
    printf("num=%d\n", num);
}

CodePudding user response:

Just check for correct number of command-line arguments before calling atoi. If not correct, then throw error and return.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: %s <number>\n", argv[0]);
        return -1;
    }

    int num = atoi(argv[1]);
    printf("num = %d\n", num);
}

CodePudding user response:

argv is a pointer. argv[i] is a string. argv[0] will be the program name so argv[1] onwards are the cmd line args.

int main(int argc, char **argv)    
{   
    int num;
    if(argc<2)  /* user has not provided any cmd line args */
    {
        printf("Enter the number : ");
        scanf("%d",&num);
    }
    else
    {
        num = atoi(argv[1]);
    }
    printf("Number = %d\n",num);
}
  • Related