In: Computer Science
I have written code in C programming that checks where the command line arguments are floats or not. For example, if I type "./math 1 1 0 0 2.5 3" in the terminal, my program realizes they are all floats but if I type "./math 1 1 0 0 2.5 g", it recognizes that not all arguments are floats and gives an error message. I want to take my code further such that after typing in "./math 1 1 0 0 2.5 3" I want to add two flags. the first flag being "-f" which tells the code what kind of calculation you want it to do with those 6 numbers before it and a second flag which can either be "-r" for radians or "-d" for degrees. The question is how do I scan if those two flags using code? So while my code checks if the 6 numbers are floats, I do not know how to check for those two flags... an example of the command line argument is "./math 1 1 0 0 2.5 3 -f -d"
Hello, you need to take all arguments as string i.e char array, and first check for the flag which starts with '-' symbol.
Then for operands check if it not start with '-', then convert it according to math calculation type i.e float/ integer.
Here is the example how you do this:
Here is the text code:
#include <stdio.h>
#include <stdlib.h>
/* declared sum constant */
const int UNKNOWN_TYPE = -1;
const int DEGREE_TYPE = 0;
const int RADIAN_TYPE = 1;
const int CALC_FLOAT = 0;
const int CALC_INT = 1;
int main(int argc, char *argv[])
{
/* read and store from command line argument */
int degreeOrRadian = UNKNOWN_TYPE;
int calcType = UNKNOWN_TYPE;
/* Loop through all arguments */
for(int i=1; i<argc; i++)
{
/* Get the argument */
char *arg = argv[i];
/* Check if it is flag */
if(arg[0] == '-')
{
/* store the flag in variable */
switch(arg[1])
{
case 'f':
calcType = CALC_FLOAT;
break;
case 'i':
calcType = CALC_INT;
break;
case 'd':
degreeOrRadian = DEGREE_TYPE;
break;
case 'r':
degreeOrRadian = RADIAN_TYPE;
break;
default:
printf("Unknown flag: %s\n", arg);
}
}
}
/* If -d flag is passed, it is degree */
/* else if -r passed, it is radian */
if(degreeOrRadian == DEGREE_TYPE)
{
printf("Degree Calculation\n");
}
else if(degreeOrRadian == RADIAN_TYPE)
{
printf("Radian Calculation\n");
}
/* check for -f flag or any flag you need */
if(calcType == CALC_FLOAT)
{
printf("Calculation type: Float\n");
float sum = 0;
/*Loop through argument and check if it is not flag */
/* then it must be operands */
for(int i=0; i<argc; i++)
{
if(argv[i][0] != '-')
{
/* convert argument to float/double */
sum += atof(argv[i]);
}
}
printf("Calculate result: %.4f",sum);
}
else if(calcType == CALC_INT)
{
printf("Calculation type: Integer\n");
int sum = 0;
for(int i=0; i<argc; i++)
{
if(argv[i][0] != '-')
{
/* Convert argument to integer */
sum += atoi(argv[i]);
}
}
printf("Calculate result: %d",sum);
}
else
{
printf("Unknown calculation type\n");
}
return 0;
}
Output