1

I'm new to C programming. I've been practicing use of command line arguments in C. I've written a C code to calculate the area and circumference of a circle. This is my code:

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

float circle(float pi,int r)
{
    float cir;
    cir=(pi*r*r);
    printf("area of the circle is: %f \n",cir);
}
float circumference(float pi,int r)
{
    float circum;
    circum=(2*pi*r);
    printf("the circumference is: %f \n",circum);
}
int main(int argc,char *argv[])
{   int r,r1;
    float pi;
    r=0;
    pi=M_PI;
    if(argc>3 || argc<3)
    {
        printf("error \n");
        exit(0);
    }
    r=atoi(argv[1]);
    r1=atoi(argv[2]);
    circle(pi,r);
    circumference(pi,r1);
}

My results are proper but I want to enhance my code to stop if the argument given is not a number. if not it should be an error. How can I do it? Any leads will be appreciated. Thank you in advance

2
  • One possibility is to use isdigit. Commented Jun 14, 2020 at 22:17
  • Thank you for replying. How can I use isdigit for multiple argument @1201ProgramAlarm Commented Jun 14, 2020 at 22:23

1 Answer 1

1

Unfortunately, atoi returns 0 if parsing fails, though 0 might be a valid input as well.

In C, I see two options to overcome this:

(1) use sscanf and see if exactly one number could be parsed:

if (sscanf(argv[1],"%d",&r) != 1) {
   // some error handling here...
}

(2) check if at least the first character is a digit (yielding a valid number then):

if (!isdigit(argv[1][0]) {
   // some error handling here...
}

But note that you may have to consider - or + and white spaces as well.

So I'd actually prefer option 1.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much.
Both of those cases will accept the string "3mice" as the value 3. That may or may not be good enough for your purpose.
thankyou for replying that made me think of a new test case @HAL9000
@HAL9000 That could be covered by checking sscanf(argv[1],"%d %c",&r,&c) == 1 where char c; would be another variable to catch any unwanted characters coming after the number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.