Search code examples
ccommand-lineuser-input

Command line and user input


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

int main(int argc, char *argv[] )
{
    float out_radius,in_radius,area, perimeter, in_radius2, out_radius2;
    
    if (argc == 1) {
        printf("Enter inner radius of ring: ");
        scanf("%f",&in_radius);
        printf("Enter outer radius of ring: ");
        scanf("%f",&out_radius);
        perimeter= (2 * 3.14) * (in_radius + out_radius);
        area= 3.14 * ((in_radius * in_radius) + (out_radius * out_radius));
    }
    
    else if (argc > 1 || argc == 2) {
        in_radius2 = atof(argv[1]);
        out_radius2 = atof(argv[2]);
        perimeter = (2 * 3.14) * (in_radius2 + out_radius2);
        area = 3.14 * ((in_radius2 * in_radius2) + (out_radius2 * out_radius2));
    }
    
    printf("Area of circle: %.2f \nPerimeter of circle: %.2f\n",area,perimeter);
}

This is a simple program that calculates the perimeter and radius when given the inner and outer radius as user input. I'm trying to make it so the user has the option to either enter the radius via user input or command line (whichever the user decides to use). I tried to create and if and else if statement to check whether the user enters data in the command line or not. My problem is when I enter the radius via the command line, I get 0 or sometimes the wrong answer as my perimeter and area. What would I need do to fix this?

Edit fixed code:

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

int main(int argc, char *argv[] )
{
    float out_radius,in_radius,area, perimeter, in_radius2, out_radius2;
  
    if (argc == 3) {
        in_radius2 = atof(argv[1]);
        out_radius2 = atof(argv[2]);
        
    }
   
    else {
        printf("Enter inner radius of ring: ");
        scanf("%f",&in_radius);
        printf("Enter outer radius of ring: ");
        scanf("%f",&out_radius);
    }
    perimeter = (2 * 3.14) * (in_radius2 + out_radius2);
    area = 3.14 * ((in_radius2 * in_radius2) + (out_radius2 * out_radius2));
    
    printf("Area of circle: %.2f \nPerimeter of circle: %.2f\n",area,perimeter);
}

Solution

  • argc is:

    If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, ... C17dr § 5.1.2.2.1 2

    If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name ....

    Change logic

    if (argc == 3) {
      // Don't need to read inputs. Use argv[1], argv[2] as pointers to strings
    } else {
      // Read inputs
    }
    

    Hmmm, OP's changing code - hard to answer a moving target.